- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我最近必须重写 Java 中的 equals
和 hashCode
方法。因此,我寻找一种快速有效的方法来计算哈希码。
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.
关于java - 您能解释一下计算哈希码的所谓 Java 标准方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11012224/
我是一名优秀的程序员,十分优秀!