答:
重写equals()就一定要重写hashCode()方法是为了:方便java.util.Map
包下的HashMap和HashSet的添加操作。
HashMap,HashSet集合添加元素时要进行两次检查,检查hashcode是否相等发生hashcode碰撞时再检查equals是否相等,两个都不相等才能添加这个元素,保证元素不重复。
而hashcode实际上是栈在堆的引用数据的索引,所以不同对象的hashcode一定不同。即使它们的内容相同。
举个例子
Student s1 = new Student("lisi",12);
Student s2 = new Student("lisi",12);
这两个对象的hashcode一定不同,set添加的时候没有hash碰撞,所以直接添加。
而实际上这两个对象里的数据完全一致,这就需要我们更爱hashcode,从比较对象的hashcode变为比较对象里的元素的hashcode之和。
我们再回到Object类说起,Objiecr类的equals()是对两个对象的内存地址进行判断,hashcode()也只是返回对象的内存地址。所以,我们如果想判断两个对象的里面的数值是否相等,是一定需要更改equals()的,而如上所说,只有比较hashcode后发生了hash碰撞才会调用equals(),所以hashcode也要更改。
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
同时这样重写也能提高效率。
小补充:String对equals和hashcode的重写:
String中的equals
1.同一对象 (true)
2.同一类型&&长度相等&&值相等 ( true)