java - 在 eclipse-Java 中重写 hashCode()

标签 java jakarta-ee overriding hashcode

每当我使用 eclipse“源”菜单覆盖 hashcode() 时,它都会在类中生成以下代码

final int prime = 31;
int result = 1;
result = prime * result + ((fieldName1== null) ? 0 : fieldName1.hashCode());
result = prime * result + ((fieldName2== null) ? 0 : fieldName2.hashCode());

谁能解释一下为什么它要进行所有这些计算(乘法然后加法),为什么它不简单地返回

fieldName.hashCode();
or
fieldName2.hashCode();

最佳答案

相乘减少collisions .

请阅读Joshua Bloch

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 - 在 eclipse-Java 中重写 hashCode(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17107920/

相关文章:

java - OSGi 将 bundle 监听器添加到已安装的 bundle 中

java - 如何过滤掉List<A>的元素,让List<A>只包含distinct A.getId()的元素?

java - “hello world” Java错误: Couldn't find it being resolved

java - 如何动态地将arraylist放入Hashmap中?

java - Android onBackPressed() 没有被调用?

python - 如何覆盖 Python 导入?

Java,在不知道参数的情况下强制执行方法

java - 如何为elasticsearch中的单个字段分配恒定的提升值?

java - 新的 .xhtml 页面不会呈现任何 jsf 标签,但以前创建的页面在同一个项目中仍然可以正常工作

java - BigInteger 乘法中的前导零