String类中的HashCode方法一直没有深入的了解,今天特地记录一下整个学习过程。
首先,上源码:
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;
}
源码中自带的说明翻译一下:
Returns a hash code for this string. The hash code for a {@code String} object is computed as s[0]*31^(n-1) + s[1]*31^(n-2) + … + s[n-1] using {@code int} arithmetic, where {@code s[i]} is the ith 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.
用法:
哈希码用于表示对象的特征,可以用于判断对象是否相等。
其他补充:
String hashCode 方法为什么选择数字31作为乘子,从网上转载一篇,说的很详细:https://juejin.im/entry/5a70af74518825732739e873
JDK源码中的Hash原理,同样转载了一篇
https://www.zhihu.com/question/20733617