String类中hashcode的计算方法

这个问题在面试中被问到过,面试官问我怎么计算String的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;
    }

可以发现,计算hashcode的最主要代码是 h = 31 * h + val[i]; 

写成公式为hashcode=\sum_{i=0}^{length-1}val[i]*31^{n-i-1}

至于为什么乘数因子是31,可以看看这篇文章

为什么String的hashCode选择 31 作为乘子_淡然坊-CSDN博客


版权声明:本文为haohulala原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。