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

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 13,526评论 5 6
  • 在完成上述工作后,就可以进入流程,首先我们确定初始化定时器后应该在什么时候启动定时器,很明显要有接口传入的数据后才...
    hoggenWang阅读 165评论 0 0
  • 一、本次复盘基本情况 (一)复盘主题 找工作的事情 (二)基本信息 复盘时间:2015/10/30 复盘地点:办公...
    唯吾德昕阅读 278评论 0 0
  • 九寨沟,因沟内有九个藏族寨子而得名。位于四川省阿坝藏族羌族自治州九寨沟县漳扎镇,距离成都540公里,车程8...
    葬爱东少i阅读 547评论 0 1
  • 11
    疼哥阅读 595评论 0 51