HashMap 是使用頻率最高的類型之一,同時也是面試經常被問到的問題之一,這是因爲 HashMap 的知識點有很多,同時它又屬於 Java 基礎知識的一部分,因此在面試中經常被問到。
本課時的面試題是,HashMap 底層是如何實現的?在 JDK 1.8 中它都做了哪些優化?
在 JDK 1.7 中 HashMap 是以數組加鏈表的形式組成的,JDK 1.8 之後新增了紅黑樹的組成結構,當鏈表大於 8 並且容量大於 64 時,鏈表結構會轉換成紅黑樹結構,它的組成結構如下圖所示:
數組中的元素我們稱之爲哈希桶,它的定義如下:
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(valu