hashcode 讨论总结

本文探讨了Java中对象的equals()方法与hashCode()方法之间的关系,阐述了对象相等时其hashCode必然相同,但不相等时hashCode可能相同。重点介绍了String类的hashCode实现方式及对哈希表性能的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最主要的结论是如果两个对象相等(equals()),那么它们的hashCode一定相同,但如果两个对象不同,它们的hashCode也有可能相同。这个结论供我们对类似生成ID这样的对象标志的算法的选择上提供参考。

 

The text with italic style is from javadoc

1) if two objects are equal, then their hashCode must be the same
2) if two objects are not equal, their hashCode do NOT have to be distinct.
   It is not required that if two objects are unequal according to the equals(java.lang.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 hashtables.
3) Class String overrides function hashCode(), it's implemented by the calculations on the string values.

4) contract #1 and #2 also work for class String, despite that it overrides function equals() and hashCode()
5) Typically, hashCode() for java.lang.Object is implemented by converting internal address of the object to an integer, therefore, on 32bit platform, As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. 
6) function hashCode() will be used for hashtable, so the confliction rate will impact the performance.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值