equals和hashcode

equals以及hashcode

1、为什么覆盖equals的时候,必须覆盖hashCode方法

2、hashco的基本实现

--------------------------------------------------

重写equals方法需要注意的:

1、自反性 A.equals(A)

2、对称性 A.equals(B) <=> B.equals(A)

3、传递性 A.equals(B)、B.equals(C) => A.equals(C)

4、一致性 A.equals(B) 什么时候都要equals

ps、

一个程序员类

@Data
public class Programer{
  private String name;
  private int age;  
}

 

重写equals方法

public boolean equals(Object obj){
  if(this == obj){
    return true;
  }  
  if(obj instance of Programer){
    Programer that = (Programer)obj;
    return that.name.equals(this.name)
        && that.age == this.age;
  }
  return false;
}

如何重写hashCode

public int hashCode(){
 int hash = 20;
 hash = 31* hash + name.hashCode();
 age = 31 * hash + age.hashCode();
}

 

意思类中的每个元素都需要在hashCode中有所表现

因为比如在hashSet中判断元素是否重复

是通过是hashCode对应的bucket中是否有相关的元素

如果hashCode没有覆盖,那么本来equals的对象就不会在一个bucket中了

 

原文地址:https://www.cnblogs.com/zhangchiblog/p/11918858.html