需要证明/分解字符串.哈希码()方法在java中

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

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

在我的教科书中,我举了“猫”这个词的例子。

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

最终值的给定方式为67,510

我对这个值的来源感到非常困惑,特别是,用于单个字符的值。我尝试了37,66和85(分别使用大写C,小写a和t的Unicode字符)。这是无效的。有人可以为我照亮这个吗?

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


温温酱
浏览 96回答 2
2回答

波斯汪

67 * 31^2 + 97 * 31^1 + 116 * 31^0 =  67 * 31^2 + 97 * 31 + 116 =  64387 + 3007 + 116 =  67510从 http://www.asciitable.com/ 中获取67,97和116

汪汪一只猫

字符串哈希代码执行以下操作:public int hashCode() {&nbsp; &nbsp; int h = hash;&nbsp; &nbsp; if (h == 0 && value.length > 0) {&nbsp; &nbsp; &nbsp; &nbsp; char val[] = value;&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < value.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; h = 31 * h + val[i];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; hash = h;&nbsp; &nbsp; }&nbsp; &nbsp; return h;}因此,基本上每次迭代都会将现有哈希值乘以31,然后将下一个值添加到哈希值中。所以当“C”= 67,“a”= 97,“t”= 116时,你得到:h = 0h *= 31;h += 67; // 'C'&nbsp; &nbsp;h *= 31;h += 97; // 'a'h *= 31;h += 116;h ==> 67510
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java