String 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;
}
@Test
public void test() {
//【对应Unicode字符集编码值a97;b98;c99】
String s = new String("abc");
//验证方式1、公式h=31 * h + val[i];
//h=31*0+97=97
//h=31*(31*0+97)+98=31*97+98=3105
//h=31*[31*(31*0+97)+98]=31*3105+99=96354
System.out.println(96354 == s.hashCode());//true
//验证方式2:hashCode()计算公式:s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
//h=97*31^(3-1)+98*31(2-1)+99*31(1-1)=96354
}
标签:String,val,int,31,hashcode,98,97
From: https://www.cnblogs.com/haveanicedayfh/p/17129396.html