[Java基础]--String hashCode实现

hashCode是java.lang.String类提供的方法(自从jdk1.0以来就有的),摘取关键的源码实现如下:

1、声明变量

 /** The value is used for character storage. */
    private final char value[];

 /** Cache the hash code for the string */
    private int hash; // Default to 0


2、hashCode方法的实现

  /**
     * 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;
    }


3、举例说明hashCode算法



4、例子中的说明

(1)0x7FFFFFFF介绍

F的二进制码为 1111
7的二进制码为 0111

0x是16进制的标识,0x7FFFFFFF代表十六进制的最高位是0,那么它与任何数做&运算都是正数


(2)为什么要对hashcode做&运算

因为有些对象的hashcode的最大值会超过Int类型的最大值,为了避免出现负数,我们必须保证为正。


(3)hashCode的计算

为什么字符串"ABC"的HashCode是64578

计算过程如下:

先确认字符的ASCII码,A=65、B=66、C=67

再利用公式

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

strHashCode=65*31^(3-1)+66*31^(3-2)+67*31^(3-3)=65*31^2+66*31+67=64578



参考:

http://blog.csdn.net/exceptional_derek/article/details/9074137

http://www.cnblogs.com/chenssy/p/3651218.html

http://blog.csdn.net/cwj649956781/article/details/8589981



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

往事随风ing

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

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

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

打赏作者

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

抵扣说明:

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

余额充值