/**
* Returns a hash code for this string. The hash code for a
* {@code String} object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* </pre></blockquote>
* using {@code int} arithmetic, where {@code s[i]} is the
* <i>i</i>th character of the string, {@code n} is the length of
* the string, and {@code ^} indicates exponentiation.
* (The hash value of the empty string is zero.)
*
* @return a hash code value for this object.
*/
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作为乘子,有几个原因:
1、31是质数,作为乘子可以减少hash碰撞,这需要依靠数学来证明。
2、31 = (1 << 5 ) -1,移位效率高,JVM为此做了性能优化。
3、除了31,还有很多其他的质数(如2, 11, 41),为什么不用,主要是31是一个折中的数字,不大不小,性能也可兼顾。