gpt4 book ai didi

java - 如何手工计算一个字符串的哈希码?

转载 作者:搜寻专家 更新时间:2023-11-01 01:02:34 24 4
gpt4 key购买 nike

我想知道如何手动计算给定字符串的哈希码。我知道在 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 位结果,我该怎么办?上面的 Long whatever 等于 -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;
}

关于java - 如何手工计算一个字符串的哈希码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3795400/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com