需要在Java中对String.hashCode()方法进行证明/分解

时间:2019-04-09 10:21:27

标签: java hashcode

我知道String.hashCode()方法采用的公式如下:

S0x31(n-1)+s1x31(n-2)+…+s(n-1)

在我的教科书中,给出了Cat一词的示例。

'C'  x31^2 + 'a' x 31 +t

最终值为67,510

我对于这个值是从哪里得出的,尤其是各个字符使用了什么值,感到非常困惑。我已经尝试过37、66和85(分别使用大写字母C的Unicode字符,小写a和t)。这是无效的。有人可以帮我照一下吗?

遗憾的是,这是我的教科书中给出的唯一示例,并且没有尝试澄清或解释它。

2 个答案:

答案 0 :(得分:0)

[{'favorited': False}, {'retweeted': False}]

其中67、97和116来自http://www.asciitable.com/

答案 1 :(得分:0)

字符串hashCode可以:

awaiting

因此,基本上每次迭代都会将现有哈希值乘以31,然后将下一个值添加到哈希值中。

因此,如果'C'= 67,'a'= 97,'t'= 116,您将得到:

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