美文网首页
Java中String类的hashCode()方法中的魔术数:3

Java中String类的hashCode()方法中的魔术数:3

作者: CrazyOrr | 来源:发表于2017-05-12 15:15 被阅读0次

Java中String类的hashCode()方法实现如下:

public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}

可以看到,循环中的每一步都对上一步的结果乘以一个系数31,那么,这个31又是怎么来的呢?
在《Effective Java》第二版的 Item 9: Always override hashCode when you override equals 中我们找到了答案:

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.

归纳如下:

  • 奇数,乘法运算溢出时不丢失信息
  • 质数,传统做法
  • 可优化 31 * i == (i << 5) - i

相关文章

网友评论

      本文标题:Java中String类的hashCode()方法中的魔术数:3

      本文链接:https://www.haomeiwen.com/subject/xowztxtx.html