关于java:Arrays.hashCode是如何实现的?

How is the Arrays.hashCode implemented?

本问题已经有最佳答案,请猛点这里访问。

我在读下面提供的Arrays.hashCode的代码,

1
2
3
4
5
6
7
8
9
10
11
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类:

1
2
@HotSpotIntrinsicCandidate
public native int hashCode();

如何计算每个迭代的element.hashCode()

谢谢您。


从《有效Java》看:

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.