gpt4 book ai didi

java - 您能解释一下计算哈希码的所谓 Java 标准方法吗?

转载 作者:行者123 更新时间:2023-11-29 08:06:12 25 4
gpt4 key购买 nike

我最近必须重写 Java 中的 equalshashCode 方法。因此,我寻找一种快速有效的方法来计算哈希码。

Java 开发人员似乎同意以下方法:

    int hash = 23;
hash = hash * 37 + paramOne;
hash = hash * 37 + paramTwo;
// And so on...

这可能是简单的算术,但我不太明白。有哪些保证?什么是角落案例?是否有更好(相当简单)的方法来做到这一点?

谢谢!

最佳答案

用 Joshua Bloch 的话(解释 String 类中 hashCode() method 的默认实现,即:s[0]*31 ^(n-1) + s[1]*31^(n-2) + ... + s[n-1]):

The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, as multiplication by 2 is equivalent to shifting. The advantage of using a prime is less clear, but it is traditional. A nice property of 31 is that the multiplication can be replaced by a shift and a subtraction for better performance: 31 * i == (i << 5) - i. Modern VMs do this sort of optimization automatically.

如需进一步阅读,请参阅 thisthis .

关于java - 您能解释一下计算哈希码的所谓 Java 标准方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11012224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com