美文网首页
hashCode()的常数31详解

hashCode()的常数31详解

作者: 王月亮17 | 来源:发表于2024-03-16 17:06 被阅读0次

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

相关文章

  • hashCode

    hashcode() 方法详解 hashCode()方法给对象返回一个hash code值。这个方法被用于hash...

  • hashcode详解

    hashcode详解 由于不会这个知识点,百度查找,具体参考文献如下:https://www.cnblogs.co...

  • Hashcode详解

    Hashcode的特性 Hashcode主要用于查询的快捷性,如Hashtable,HashMap等,Hashco...

  • HashMap中为什么数组的长度为2的幂次方

    Java中HashCode算法详解 Java中的集合,比如HashMap/HashSet/HashTable在实现...

  • java note

    java hashcode 31 https://segmentfault.com/a/1190000010799...

  • Fundamentals

    Java中原生(native)函数的用法 详解 equals() 方法和 hashCode() 方法 如何正确实现...

  • hashcode-02-25

    hashcode就是用地址转换的一个hash值。 hash就是以常数平均时间插入,删除,索引的一种技术。 hash...

  • hashcode返回0会出现什么问题

    重写hashcode的时候都是按照推荐方法,从来没有仔细考虑为什么不可以直接返回一个常数 结论 hashmap是通...

  • Java中==、equals()、hashCode()详解

    原创在这里:http://yanhui.site/2017/09/09/JavaInterview%E2%80%9...

  • 2020-01-02

    UIStackView 的 distribution 属性详解 原创Sodaslay 发布于2017-12-31 ...

网友评论

      本文标题:hashCode()的常数31详解

      本文链接:https://www.haomeiwen.com/subject/ksbnzdtx.html