/**
* Returns a hash code for this string. The hash code for a
* <code>String</code> object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* </pre></blockquote>
* 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.)
*
* @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;
}
按照上面源码举例说明:
String msg = "abcd"; // 此时value[] = {'a','b','c','d'} 因此
for循环会执行4次
第一次:h = 31*0 + a = 97
第二次:h = 31*97 + b = 3105
第三次:h = 31*3105 + c = 96354
第四次:h = 31*96354 + d = 2987074
由以上代码计算可以算出 msg 的hashcode = 2987074 刚好与 System.err.println(new String("abcd").hashCode()); 进行验证
在源码的hashcode的注释中还提供了一个多项式计算方式:
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
s[0] :表示字符串中指定下标的字符
n:表示字符串中字符长度
a*31^3 + b*31^2 + c*31^1 + d = 2987074 + 94178 + 3069 + 100 = 2987074 ;
注意:
关于为什么使用31的文章很多,其中[1]比较有代表性,基本有以下几点结论:
31是质数,能够让计算的结果尽可能分布均匀
31并不是最好的但是安全可靠
另外,基本数据的hashCode函数的写法都相对比较简单,可以参见[2]。
[1] 科普:String hashCode 方法为什么选择数字31作为乘子, https://yq.aliyun.com/articles/665663?utm_content=m_1000022808
[2] Java基本数据类型的 hashCode源码, https://blog.csdn.net/g_y_x_/article/details/83059297