关于hashCode你必须要知道的三件事

在java中,hashCode()和equals( )要遵守的规范:

Objects that are equal must have the same hash code 
within a running process

在运行时,相互equals的对象必须拥有相同的hash code

逆命题:相同hash code的对象相等(equals)。
否命题:不相等的的对象(equals)拥有不同的hash code。
逆否命题:hash code 不同的对象不相等(equals)。

在遵循规范的情况下,原命题为真,只有逆否命题为真。

同时,理论上有很大几率,不同的对象有相同的hashcode,因为对象的hashCode() 方法返回一个int,最多有2^32中hashcode,而在64位虚拟机中,理论上对象可以存在2^64个(直到引用耗尽为止)。因此对象和hashCode之间不可能存在一对一的关系。

Whenever two different objects have the same hash code, 
we call this a collision.

当两个不同的对象拥有相同的hashcode时,我们称其为冲突。

A collision is nothing critical, it just means that there 
is more than one object in a single bucket, so a HashMap 
lookup has to look again to find the right object. A lot of
collisions will degrade the performance of a system, but 
they won’t lead to incorrect results.

有冲突并不是什么大事,只是意味着在HashMap中两个对象会被放到一个桶,所
以在查询的时候会多查找一次。太多的冲突会造成性能的降低(退化为
linkedlist),但是并不会产生错误。

But if you mistake the hash code for a unique handle to an 
object, e.g use it as a key in a Map, then you will 
sometimes get the wrong object. Because even though 
collisions are rare, they are inevitable. For example, the 
Strings "Aa" and "BB" produce the same hashCode: 2112. 

但是你如果将对象的hascode错误的当做key来用,往往会出错,因为如上所说
不同的对象可能会有相同的hashcode。因此要遵循下面的第二条原则。
HashCodes can change hashcode是可变的

一方面,对于可变对象,由于hashCode一般根据其内部状态进行计算,当对象的
内部状态改变时,hashCode就会发生改变;

另一方面,根据javadoc,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.

因此:

  1. Whenever you implement equals, you MUST also implement hashCode。当你实现equals方法时,你必须也实现hashCode方法。
  2. Never misuse hashCode as a key。不要将hashCode做key。
  3. Do not use hashCode in distributed applications 不要在分布式应用中依赖hashCode。

另一个替代品SHA1

You may know that cryptographic hash codes such as SHA1 are
sometimes used to identify objects (Git does this, for 
which makes collisions virtually impossible. Even with a 
gigantic number of objects, the odds of a collision in this 
space are far below the odds of a meteor crashing the 
computer that runs your program. 

你可能听说过密码学里的散列码,比如SHA1,用它来作为对象id,git就是这样
做的。这样做安全吗?也不是绝对安全的,SHA1使用了160比特,这也有可能导
致冲突。但即使产生了数量非常巨大的objects,产生冲突的可能性比彗星撞地
球的几率还要低

原文:http://eclipsesource.com/blogs/2012/09/04/the-3-things-you-should-know-about-hashcode/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值