实现hashCode()的首选方法是什么? [英] what is the preferred way of implementing hashCode()?

查看:148
本文介绍了实现hashCode()的首选方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我需要通过组合其几个实例成员的hashCodes来实现obj的hashCode()方法。例如,如果组合obj有成员a,b和c,我经常看到ppl将其实现为

Sometimes I need to implement an obj's hashCode() method by combining the hashCodes of its several instance members. For example, if the combinational obj has members a, b, and c, I often see ppl implement it as


int hashCode(){
   return 31 * 31 * a.hashCode() + 31 * b.hashCode() + c.hashCode();
}

这个神奇的数字31来自哪里?它是4字节的长度还是仅仅是素数?

Where does this magic number 31 come from? Is it the length of 4-bytes or just a prime number?

是否有其他优选/标准的方法来实现hashCode()?

Is there any other preferred/standard way of implementing hashCode()?

推荐答案

参见有效的Java配方。它只是最好的来源,放下手。

See Effective Java's recipe. It's just the best source, hands down.

使用素数只是为了在不知道域的情况下尝试获得相当好的分布。溢出到相同的值需要一段时间。如果我没记错的话,值31非常随意。

The use of a prime number is just to try to get a reasonably good distribution without knowing the domain. It will take a while to overflow to the same value. The value 31 is pretty arbitrary if I recall correctly.

根据Bloch(他使用17作为初始值,37作为常数乘数):

According to Bloch (he uses 17 as an initial value and 37 as the constant multiplier):


使用非零初始值(...),因此哈希值将受
初始字段的影响,其哈希值(...)是零。如果将零用作
的初始值(...),则整个哈希值将不受任何此类
初始字段的影响,这可能会增加冲突。值17是任意的。

...

选择乘数37是因为它是一个奇数素数。如果它是偶数且
乘法溢出,则信息将丢失,因为将
乘以2相当于移位。使用素数的优点明显少于
,但为此目的使用素数是传统的。

A nonzero initial value is used (...) so the hash value will be affected by initial fields whose hash value (...) is zero. If zero was used as the initial value (...) the overall hash value would be unaffected by any such initial fields, which could increase collisions. The value 17 is arbitrary.
...
The multiplier 37 was chosen because it is an odd prime. If it was even and the multiplication overflowed, information would be lost because multiplication by two is equivalent to shifting. The advantages of using a prime number are less clear, but it is traditional to use primes for this purpose.

这篇关于实现hashCode()的首选方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆