重写equals方法为什么要重写hashcode方法
Note that it is generally necessary to override the {@code hashCode}
* method whenever this method is overridden, so as to maintain the
* general contract for the {@code hashCode} method, which states
* that equal objects must have equal hash codes.
*
我们在Object类中看equls方法 特别申明:@code hashCode}方法的一般约定,它声明*相等的对象必须有相等的哈希代码,我们看下hashcode方法
public native int hashCode();
是一个本地方法栈方法,是被native修饰 返回该对象大hash值,那hash 值是什么那
,As much as is reasonably practical, the hashCode method defined by
* class {@code Object} does return distinct integers for distinct
* objects. (This is typically implemented by converting the internal
* address of the object into an integer, but this implementation
* technique is not required by the
* Java™ programming language.)
也就是 返回该对象内部地址hash算法后返回Integer类型整数,通俗来说就是这个对象在堆中的引用地址。
知道eqlus和hashcode方法是做什么了,我们就很很容易回答,为什么重写equals 方法就必须要重写hashcode方法了,
我总结下 原因
1.equls方法默认是比较的对象大引用,而hashcode返回的是对象的引用,重写equals方法已经改变原有比较方法,如不重写hashcode方法,那hashcode方法仍然是对象的地址引用,这样就会得到对象不一样,可重写equals中返回值true的情况
比如
public class BaseFace {
public static void main(String[] args) {
Object o = new Object();
A a1 = new A("A","A");
A a2 = new A("A","B");
System.out.println(a1.equals(a2));
}
}
class A{
public String key;
public String value;
public A(){};
public A(String key,String value) {
this.key = key;
}
public boolean equals(A a) {
return (key == a.key);
}
}
这样是不一致大,客观上说 equals是 比不出对象是否一样的
引申一下,什么情况下我们会重写equals方法呢
一般是对象时候,即使引用地址不同,对象内的属性可能相同的时候,我们就需要根据对象内属性来判断对象是否相等