重写equals 为什么要重写hashCode方法

本文详细解读了Java中Object类的hashCode方法的注释规约,包括:同一对象多次调用hashCode应返回相同值,equals相等的对象hashCode必须相同,不相等的对象hashCode不一定不同。还讨论了重写equals时如何相应地调整hashCode实现,以优化散列表性能。
摘要由CSDN通过智能技术生成

来源
https://www.jianshu.com/p/3819388ff2f4

Object类的hashCode()方法有如下的注释, 定义了hashCode方法的三个规约

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(Object) method, then calling the hashCode method on each of the 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.

翻译成中文如下 :

  • 在应用程序的执行期间,只要对象的equals方法的比较操作所用到的信息没有被修改,那么对同一个对象的多次调用,hashCode方法都必须始终返回同一个值。在一个应用程序与另一个应用程序的执行过程中,执行hashCode方法所返回的值可以不一致。

  • 如果两个对象根据equals(Object)方法比较是相等的,那么调用这两个对象中的hashCode方法都必须产生同样的整数结果

  • 如果两个对象根据equals(Object)方法比较是不相等的,那么调用这两个对象中的hashCode方法,则不一定要求hashCode方法必须产生不用的结果。但是程序员应该知道,给不相等的对象产生截然不同的整数结果,有可能提高散列表的性能。

equals 方法默认的是比较内存地址是否相等, 重写之后, 一般用于比较对象中成员变量的值是否相同.
hashCode 默认是调用native方法 ,返回的也是内存地址.

按照hashCode 规约中第二条, equals相同, hashCode必须相同, 因此只要重写了equals方法, 那么这个对象的hashCode值也要根据成员变量去计算出其hashCode值, 而不是返回默认的内存地址. 否则就会造成equals相同, hashCode不同.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值