gpt4 book ai didi

java - 为什么选择 31 在 hashcode() 实现中进行乘法运算?

转载 作者:搜寻专家 更新时间:2023-11-01 01:13:48 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Why does Java's hashCode() in String use 31 as a multiplier?
Why use a prime number in hashCode?

来自 Effective Java 第 9 项:在覆盖 equals 时始终覆盖 hashCode考虑以下覆盖 Object 类中定义的 hashcode() 的相关代码片段。

public final class PhoneNumber {
private final short areaCode;
private final short prefix;
private final short lineNumber;
......//Rest ignored on purpose
.....

private volatile int hashCode; // (See Item 71)
@Override public int hashCode() {
int result = hashCode;
if (result == 0) {
result = 17;
result = 31 * result + areaCode;
result = 31 * result + prefix;
result = 31 * result + lineNumber;
hashCode = result;
}
return result;
}
}

我理解为什么选择非零初始值“17”。我也明白乘法是在每个步骤中完成的,因此字段的顺序在计算 hashcode() 中起着重要作用。但我不明白选择 31 作为乘法值的原因。有人可以向我解释为什么吗?这就是 Bloch 对 31 所说的话,但我真的不明白。我特别无法理解下面的斜体行。

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.

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