1. 程式人生 > >Java中HashSet集合如何控制 元素唯一性 總結

Java中HashSet集合如何控制 元素唯一性 總結

public int hashCode() { int h = hash; if (h == 0) { int off = offset; char val[] = value; int len = count; for (int i = 0; i < len; i++) { h = 31*h + val[off++]; } hash = h; } return h; } 解釋一下這個程式(String的API中寫到): s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] 使用 int 演算法,這裡 s[i] 是字串的第 i 個字元,n 是字串的長度,^ 表示求冪。(空字串的雜湊碼為 0。)