加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何手动计算字符串的哈希码?

发布时间:2020-12-15 05:22:38 所属栏目:Java 来源:网络整理
导读:我想知道如何手动计算给定字符串的哈希码.我知道在 Java中,你可以这样做: String me = "What you say what you say what?"; long whatever = me.hashCode(); 这都是好事和花花公子,但我想知道如何手工完成.我知道计算字符串哈希码的给定公式是这样的: S0 X
我想知道如何手动计算给定字符串的哈希码.我知道在 Java中,你可以这样做:

String me = "What you say what you say what?";  
long whatever = me.hashCode();

这都是好事和花花公子,但我想知道如何手工完成.我知道计算字符串哈希码的给定公式是这样的:

S0 X 31 ^ (n-1) + S1 X 31 ^ (n-2) + .... + S(n-2) X 31 + S(n-1)

其中S表示字符串中的字符,n表示字符串的长度.然后使用16位unicode,字符串me中的第一个字符将被计算为:

87 X (31 ^ 34)

然而,这创造了一个疯狂的大数字.我无法想象像这样将所有角色加在一起.那么,为了计算最低阶32位的结果,我该怎么办?从上面的长度等于-957986661并且我不是如何计算的?

解决方法

看一下java.lang.String的源代码.

/**
 * 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;
    int len = count;
    if (h == 0 && len > 0) {
        int off = offset;
        char val[] = value;
        for (int i = 0; i < len; i++) {
            h = 31*h + val[off++];
        }
        hash = h;
    }
    return h;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读