hash函数--hashcode()底层实现

java源码是如何生成哈希值的?

又是使用何种方法构造哈希表的
构造哈希表的方法有 
1.数组+散列函数
2.分离链表+散列函数(分离链表在结构上和邻接链表基本一致但是用的地方不一样一个用在散列表一个用在图中)
3.

String 类的hasCode方法的定义:

使用以下的函数来确定string类的原因是 string类是一个不变的类,如果string类被改变了,需要将哈希值进行重置,相同的字符串的哈希值是相同的。
31结合各个元素的ASCII值计算String类型的数据的哈希值。a的ASCII码值为97。
在这里插入图片描述

/**
     * 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的描述:

大篇幅描述判断两个对象是否修改了使用equals()函数:
最后对一般对象的hascode函数的描述:

 * As much as is reasonably practical, the hashCode method defined by class  does return distinct integers for distinct objects. 
 * 
(This is typically implemented by converting the internal  address of the object into an integer, but this implementation technique is not required by the Java&trade; programming language.)*
*在相当实际的情况下,类定义的hashCode方法确实为不同的对象返回不同的整数。
(这通常是通过将对象的内部地址转换为整数来实现的,但是Java&amp;trade;编程语言不需要这种实现技术。)*
发布了212 篇原创文章 · 获赞 32 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_42664961/article/details/104137651
今日推荐