簡單說,hash 是一種把任意內容的輸入,轉換成固定長度輸出的方式——例如固定 10 位數,再用一個稱為 HashTable 的容器來存放。
"a" ---> 1 123 ---> 2 ...
注意:輸入的可能是無窮無盡的,遠比固定長度的輸出多得多,因此必然會出現「不同輸入得到相同輸出」的情形,這就是 hash 沖突。HashMap 自然也無法免俗。
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // 負載因子,預設 0.75
threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
table = new Entry[DEFAULT_INITIAL_CAPACITY]; // 使用 Entry 陣列
init();
}
table 是 Entry 陣列,threshold 是扩容門檻(容量 × 0.75)。之所以選 0.75,是在「空間浪費」與「鏈條過長導致查詢變慢」之間取的折衷。
public V put(K key, V value) {
if (key == null) // 允許 null key
return putForNullKey(value);
int hash = hash(key.hashCode()); // 依 key 的 hashCode 再算一次 hash
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
// 位置已有且 key 相同 → 覆蓋
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
// 不存在 → 新增
modCount++;
addEntry(hash, key, value, i);
return null;
}
這裡有兩個容易忽略的細節。第一,判斷「同一個 key」的條件是 e.hash == hash && (k == key || key.equals(k))——先比 hash 再比 equals,是為了讓 equals 只在必要時才被呼叫,這也是為什麼自訂 key 類別時必須同時覆寫 hashCode() 與 equals()。第二,即使兩個 key 的 hashCode 不同,經過 hash() 攪拌後仍可能得到相同結果,所以鏈條是必要的設計而非缺陷。
/**
* 為給定的 hashCode 再做一次攪拌,用來抵消品質不佳的 hash 函式。
* 這很關鍵,因為 HashMap 使用 2 的次方長度的 hash 表。
*/
static int hash(int h) {
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
// 依 hashCode 與 table 長度計算 index
static int indexFor(int h, int length) {
return h & (length - 1);
}
hash() 把高位元資訊往下混合,讓「只差固定倍數」的 hashCode 也能被均勻分散,官方註解提到預設負載因子下大約只會有 8 次碰撞。indexFor() 則用 h & (length-1) 取代取模——因為 length 一定是 2 的次方,位元 AND 的結果與取模等價,但快得多。
void addEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex]; // 先取原元素作為 next
table[bucketIndex] = new Entry<K,V>(hash, key, value, e); // 新元素指向它
if (size++ >= threshold)
resize(2 * table.length); // 超過門檻就扩容為兩倍
}
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next; // 指向下一個
final int hash;
...
}
新元素永遠插在鏈條頭部(頭插法),所以同一 bucket 內的順序與插入順序相反。一旦元素數超過 threshold,就呼叫 resize 把容量加倍並重新分佈——這也是 HashMap 在大量寫入時偶爾會出現效能抖動的原因。
public V get(Object key) {
if (key == null)
return getForNullKey();
int hash = hash(key.hashCode());
// 先算出鏈條在 table 中的位置,再沿鏈條找出符合的 key
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
return null;
}
put 與 get 走的是同一條路徑:兩次 hash、一次 indexFor,然後在鏈條上線性搜尋。理解這一點,就能理解為什麼「良好的 hashCode 實作」與「避免在同一 bucket 塞入過多元素」是 HashMap 效能的命脈。(補充:JDK 8 之後鏈條過長會轉為紅黑樹,並在扩容時改用高低位拆分,但整體思路不變。)