有时我需要通过组合其多个实例成员的 hashCode 来实现 obj 的 hashCode() 方法。例如,如果组合 obj 具有成员 a、b 和 c,我经常看到 ppl 将其实现为
int hashCode(){
return 31 * 31 * a.hashCode() + 31 * b.hashCode() + c.hashCode();
}
这个神奇的数字 31 从何而来?是 4 个字节的长度还是一个质数?
是否有任何其他首选/标准方法来实现 hashCode()?
最佳答案
参见 Effective Java's recipe .毫无疑问,这是最好的来源。
使用质数只是为了在不知道域的情况下尝试得到一个相当好的分布。溢出到相同的值需要一段时间。如果我没记错的话,值 31 是相当随意的。
根据 Bloch(他使用 17 作为初始值,37 作为常数乘数):
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.
关于java - 实现 hashCode() 的首选方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3869252/