There is no in-depth understanding of the HashCode method in the String class. Today, I specially record the entire learning process.
First, on the source code:
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;
}
Translate the instructions that come with the source code:
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.
Usage:
Hash codes are used to represent the characteristics of objects and can be used to determine whether objects are equal.
Other additions:
Why does the String hashCode method choose the number 31 as the multiplier? I reprinted an article from the Internet and said it in great detail:
https://juejin.im/entry/5a70af74518825732739e873
The Hash principle in the JDK source code is also reproduced