以下是来自Java 8(具体为1.8.0_131) String.hashCode()
方法的源代码片段:
/**
* 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;
}
可以看到,文档说明了hashCode()
的计算公式如下:
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
虽然实际实现可能不同
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
我有什么明显的遗漏吗?请帮我看看。
1.8.0_131
。 - sanbhat