hashCode()的常数31详解

2024-03-16  本文已影响0人  王月亮17

首先看下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。
上一篇 下一篇

猜你喜欢

热点阅读