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

标签 java hash

我想知道如何手动计算给定字符串的哈希码。我知道在 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/

相关文章:

java - 如何用java定制allure报告

java - 使用翻译api后出现错误

hash - 理想的密码哈希算法是什么样的?

ruby-on-rails - Ruby:通过点击访问值

python - Python 中的滚动哈希非常快?

ruby-on-rails - 我将如何从 Ruby on Rails 中的哈希数组中分解和提取数组?

typescript - 如何检查 Typescript 中的 HashMap 是否为空

java - dbunit 数据集没有将 boolean 字段放入数据库

java - 在此求一个数列

java - mapstruct v1.3.1FINAL : imports from static methods aren't generated