最近看到一篇關於hashCode的值的問題,提到使用hashCode比較字符串相等的問題。
看了源碼,如下:
int h = hash;
int len = count;
if (h == 0 && len > 0) {
int off = offset;
char val[] = value;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
關鍵的一行:h = 31*h + val[off++];
h初始爲0,val[]是char類型的數組,val[off++]拿的是char類型字符的ASCII值
這樣一來,不同的字符串,可能會有相同的hashCode值。