Java中equals与hashcode

在JDK中,有相关约定,当a.equals(b)为true,那么a.hashcode()就必须与b.hashcode()相等,但是如果a.equals(b)为false,a与b的hashcode并没有强制要求不相等,但是正常做法应该a.equals(b)为false,那么a.hashcode也应该!=b.hashcode,因为这样可以提高hash表的性能。

以下是JDK中Object类的hashcode()注释:

The general contract of hashCode is:

  • 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.

当然,最重要的一点是,当我们要把对象作为HashMap的key时,或者放到HashSet容器中时,我们必须重写equals()和hashcode()方法,因为我们在put,get时,hashMap不只是比较了hashcode还有equals,只有两者都为true时才会认为是同一对象。


BTW:
在JDK1.7中引入了一个工具类java.util.Objects,日常使用的isNull,equals,compare我们可以使用这个工具类。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值