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原理,同樣轉載了一篇