hashCode()的常数31详解

首先看下hashCode()的源码,在String类中:

/**
     * Returns a hash code for this string. The hash code for a
     * {@code String} object is computed as
     * <blockquote><pre>
     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
     * </pre></blockquote>
     * using {@code int} arithmetic, where {@code s[i]} is the
     * <i>i</i>th character of the string, {@code n} is the length of
     * the string, and {@code ^} indicates exponentiation.
     * (The hash value of the empty string is zero.)
     *
     * @return  a hash code value for this object.
     */
    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;
    }

可以看到for循环中h = 31 * h + val[i];,循环后的公式在注释中也给出来了:s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
那为什么这里要乘31呢?乘其他数可不可以呢?
主要原因有以下几点:

  1. 31是一个奇质数,如果用偶数会导致乘积运算时溢出;
  2. 2的5次方是32,那么31 * h就等于32 * h - h,转换成位运算为(h << 5) - h,JVM支持此类自动优化,可以提升性能;
  3. 用大量单词验证,从2开始验证所有质数,到31时发生碰撞的概率就明显变小了。到199更小但是199计算出来的值会超过int最大值,该方法返回的又是int,所有从质数中取碰撞概率明显小并且数字相对最小的数字,就是31。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Counter-Strike大牛

创作不易,感谢鼓励。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值