为什么重写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.

注意每当重写此方法时,通常需要重写hashCode(),以便维护hashCode()的常规约定,该方法说明相等的对象必须具有相等的哈希代码。

       在hashCode方法中,字段要参与hash值的运算,作为hash运算的中间参数。为了遵守:2个对象equals,那么 hashCode一定相同规则。也是说,参与equals函数的字段,也必须都参与hashCode 的计算。

附jdk8源码:

Object类中hashCode();

       * two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

       两个对象必须产生不同的整数结果。然而,程序员应该知道生成不同的整数结果对于不相等的对象,可以提高哈希表的性能。

       Object类默认的equals比较规则就是比较两个对象的内存地址。而hashcode是本地方法,java的内存是安全的,因此无法根据散列码得到对象的内存地址,但实际上,hashcode是根据对象的内存地址经哈希算法得来的。
为什么重写equals要重写hashcode?_string类

Object类中equals();

为什么重写equals要重写hashcode?_string类_02

String类中hashCode();

为什么重写equals要重写hashcode?_算法_03

String类中equals();

为什么重写equals要重写hashcode?_string类_04