您当前的位置: 首页 > 

java持续实践

暂无认证

  • 2浏览

    0关注

    746博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

java持续实践 发布时间:2021-05-29 15:34:08 ,浏览量:2

来源 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不同.

关注
打赏
1658054974
查看更多评论
立即登录/注册

微信扫码登录

0.0378s