【发布时间】:2019-03-02 08:18:16
【问题描述】:
我正在阅读下面提供的Arrays.hashCode 的代码,
public static int hashCode(Object a[]) {
if (a == null)
return 0;
int result = 1;
for (Object element : a)
result = 31 * result + (element == null ? 0 : element.hashCode());
return result;
}
我发现为什么选择31 用于散列还不清楚。
其次,element.hashCode() 将我发送到定义它的 Object 类:
@HotSpotIntrinsicCandidate
public native int hashCode();
如何为每次迭代计算element.hashCode()?
谢谢。
【问题讨论】:
-
I find it's not as clear as for why 31 is chosen for the hashing.因为它的素数。 -
@tkausl 还有很多较小的素数,例如,为什么不选择
17?背后可能有一些强有力的理由。 -
它说明了为什么使用幻数不是一个好习惯。
-
@AmitBera 该链接解释得很好。很快,Java 选择了 31 来优化计算成本。
-
"element.hashCode() 是如何计算的" - 每个类都可以实现(覆盖)
hashCode方法;例如Integer只是返回它的值