Java的 String.hashCode() 实现的源码解读以及31系数

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

 按照上面源码举例说明:

String msg = "abcd";  // 此时value[] = {'a','b','c','d'}  因此

for循环会执行4次

第一次:h = 31*0 + a = 97 

第二次:h = 31*97 + b = 3105 

第三次:h = 31*3105 + c = 96354 

第四次:h = 31*96354 + d = 2987074 

由以上代码计算可以算出 msg 的hashcode = 2987074  刚好与 System.err.println(new String("abcd").hashCode()); 进行验证

 

在源码的hashcode的注释中还提供了一个多项式计算方式:

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]      

s[0] :表示字符串中指定下标的字符

n:表示字符串中字符长度

a*31^3 + b*31^2 + c*31^1 + d = 2987074  + 94178 + 3069 + 100 = 2987074 ;

 

注意:

关于为什么使用31的文章很多,其中[1]比较有代表性,基本有以下几点结论:

31是质数,能够让计算的结果尽可能分布均匀
31并不是最好的但是安全可靠
另外,基本数据的hashCode函数的写法都相对比较简单,可以参见[2]。

[1] 科普:String hashCode 方法为什么选择数字31作为乘子, https://yq.aliyun.com/articles/665663?utm_content=m_1000022808
[2] Java基本数据类型的 hashCode源码, https://blog.csdn.net/g_y_x_/article/details/83059297

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

゛Smlie。

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值