需要在java中证明/细分String.hashCode()方法

问题描述 投票:-2回答:2

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

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

在我的教科书中,我得到了Cat这个词的例子。

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

最终值为67,510

我完全混淆了这个值的来源,具体来说,是用于个别角色的值。我尝试过37,66和85(使用Unicode字符表示大写字母C,分别表示小写字母a和t)。这是无效的。有人可以为我做这个吗?

遗憾的是,这是我的教科书中唯一的例子,并没有试图澄清或解释它。

java hashcode
2个回答
0
投票
67 * 31^2 + 97 * 31^1 + 116 * 31^0 = 
67 * 31^2 + 97 * 31 + 116 = 
64387 + 3007 + 116 = 
67510

67,97和116取自http://www.asciitable.com/


0
投票

字符串hashCode:

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

所以基本上每次迭代现有的散列都乘以31,然后将下一个值添加到散列中。

所以'C'= 67,'a'= 97,'t'= 116你得到:

h = 0
h *= 31;
h += 67; // 'C'   

h *= 31;
h += 97; // 'a'

h *= 31;
h += 116;

h ==> 67510
© www.soinside.com 2019 - 2024. All rights reserved.