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;
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;
}
String 类中的
private final char value[];//缓存字符串字符
private int hash;//缓存计算出的hash值
System.out.println((int)'A');//65
//s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] --> h=31*h+val[i]
/*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.)*/
//使用整数计算,s[i]是字符串中的第i个字符(从0开始计数),n是字符串的长度,^代表指数
System.out.println("AB".hashCode());//65*31+66
System.out.println(65*31+66);
char val[] = new char[]{'A','B'};
int h = 0;
for(int i = 0; i < val.length; i ++){
h = 31*h + val[i];
}
System.out.println(h);//2081