gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:37:38 25 4
gpt4 key购买 nike

每当我使用 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/

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