HashMap 底層實現原理是什麼?JDK8 做了哪些優化?
HashMap 是使用頻率最高的類型之一,同時也是面試經常被問到的問題之一,這是因爲 HashMap 的知識點有很多,同時它又屬於 Java 基礎知識的一部分,因此在面試中經常被問到。
典型回答
在 JDK 1.7 中 HashMap 是以數組加鏈表的形式組成的,JDK 1.8 之後新增了紅黑樹的組成結構,當鏈表大於 8 並且容量大於 64 時,鏈表結構會轉換成紅黑樹結構,它的組成結構如下圖所示:
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-cIg1Gykm-1589017615094)(https://s0.lgstatic.com/i/image3/M01/73/D9/Cgq2xl5rDYmAM-0hAABv6sMsyOQ867.png)]
數組中的元素我們稱之爲哈希桶,它的定義如下:
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(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
可以看出每個哈希桶中包含了四個字段:hash、key、value、next,其中 next 表示鏈表的下一個節點。
JDK 1.8 之所以添加紅黑樹是因爲一旦鏈表過長,會嚴重影響 HashMap 的性能,而紅黑樹具有快速增刪改查的特點,這樣就可以有效的解決鏈表過長時操作比較慢的問題。
考點分析
上面大體介紹了 HashMap 的組成結構,但面試官想要知道的遠遠不止這些,和 HashMap 相關的面試題還有以下幾個:
- JDK 1.8 HashMap 擴容時做了哪些優化?
- 加載因子爲什麼是 0.75?
- 當有哈希衝突時,HashMap 是如何查找並確認元素的?
- HashMap 源碼中有哪些重要的方法?
- HashMap 是如何導致死循環的?
知識擴展
HashMap 源碼分析(1.8)
HashMap 源碼中包含了以下幾個屬性:
// HashMap 初始化長度
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// HashMap 最大長度
static final int MAXIMUM_CAPACITY = 1 << 30; // 1073741824
// 默認的加載因子 (擴容因子)
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 當鏈表長度大於此值且容量大於 64 時
static final int TREEIFY_THRESHOLD = 8;
// 轉換鏈表的臨界值,當元素小於此值時,會將紅黑樹結構轉換成鏈表結構
static final int UNTREEIFY_THRESHOLD = 6;
// 最小樹容量
static final int MIN_TREEIFY_CAPACITY = 64;
什麼是加載因子?加載因子爲什麼是 0.75?
加載因子也叫擴容因子或負載因子,用來判斷什麼時候進行擴容的,假如加載因子是 0.5,HashMap 的初始化容量是 16,那麼當 HashMap 中有 16*0.5=8 個元素時,HashMap 就會進行擴容。
那加載因子爲什麼是 0.75 而不是 0.5 或者 1.0 呢?
這其實是出於容量和性能之間平衡的結果:
- 當加載因子設置比較大的時候,擴容的門檻就被提高了,擴容發生的頻率比較低,佔用的空間會比較小,但此時發生 Hash 衝突的機率就會提升,因此需要更復雜的數據結構來存儲元素,這樣對元素的操作時間就會增加,運行效率也會因此降低;
- 而當加載因子值比較小的時候,擴容的門檻會比較低,因此會佔用更多的空間,此時元素的存儲就比較稀疏,發生哈希衝突的可能性就比較小,因此操作性能會比較高。
所以綜合了以上情況就取了一個 0.5 到 1.0 的平均數 0.75 作爲加載因子。
查詢
public V get(Object key) {
Node<K,V> e;
// 對 key 進行哈希操作
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
// 非空判斷
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 判斷第一個元素是否是要查詢的元素
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
// 下一個節點非空判斷
if ((e = first.next) != null) {
// 如果第一節點是樹結構,則使用 getTreeNode 直接獲取相應的數據
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do { // 非樹結構,循環節點判斷
// hash 相等並且 key 相同,則返回此節點
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
從以上源碼可以看出,當哈希衝突時我們需要通過判斷 key 值是否相等,才能確認此元素是不是我們想要的元素。
新增
public V put(K key, V value) {
// 對 key 進行哈希操作
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 哈希表爲空則創建表
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 根據 key 的哈希值計算出要插入的數組索引 i = (n - 1) & hash
if ((p = tab[i = (n - 1) & hash]) == null)
// 如果 table[i] 等於 null,則直接插入
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
// 如果 key 已經存在了,直接覆蓋 value
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 如果 key 不存在,判斷是否爲紅黑樹
else if (p instanceof TreeNode)
// 紅黑樹直接插入鍵值對
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
// 爲鏈表結構,循環準備插入
for (int binCount = 0; ; ++binCount) {
// 下一個元素爲空時
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
// 轉換爲紅黑樹進行處理
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// key 已經存在直接覆蓋 value
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
// 超過最大容量,擴容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
新增方法的執行流程,如下圖所示:
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-y9gGLSE1-1589017615096)(https://s0.lgstatic.com/i/image3/M01/73/D9/CgpOIF5rDYmATP43AAB3coc0R64799.png)]
擴容
final Node<K,V>[] resize() {
// 擴容前的數組
Node<K,V>[] oldTab = table;
// 擴容前的數組的大小和閾值
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
// 預定義新數組的大小和閾值
int newCap, newThr = 0;
if (oldCap > 0) {
// 超過最大值就不再擴容了
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 擴大容量爲當前容量的兩倍,但不能超過 MAXIMUM_CAPACITY
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
// 當前數組沒有數據,使用初始化的值
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
// 如果初始化的值爲 0,則使用默認的初始化容量
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 如果新的容量等於 0
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
// 開始擴容,將新的容量賦值給 table
table = newTab;
// 原數據不爲空,將原數據複製到新 table 中
if (oldTab != null) {
// 根據容量循環數組,複製非空元素到新 table
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
// 如果鏈表只有一個,則進行直接賦值
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
// 紅黑樹相關的操作
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
// 鏈表複製,JDK 1.8 擴容優化部分
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
// 原索引
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
// 原索引 + oldCap
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
// 將原索引放到哈希桶中
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
// 將原索引 + oldCap 放到哈希桶中
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
從以上源碼可以看出,JDK 1.8 在擴容時並沒有像 JDK 1.7 那樣,重新計算每個元素的哈希值,而是通過高位運算(e.hash & oldCap)來確定元素是否需要移動,比如 key1 的信息如下:
key1.hash = 10 0000 1010
oldCap = 16 0001 0000
使用 e.hash & oldCap 得到的結果,高一位爲 0,當結果爲 0 時表示元素在擴容時位置不會發生任何變化,而 key 2 信息如下:
key2.hash = 10 0001 0001
oldCap = 16 0001 0000
這時候得到的結果,高一位爲 1,當結果爲 1 時,表示元素在擴容時位置發生了變化,新的下標位置等於原下標位置 + 原數組長度,如下圖所示:
其中紅色的虛線圖代表了擴容時元素移動的位置。
HashMap 死循環分析
以 JDK 1.7 爲例,假設 HashMap 默認大小爲 2,原本 HashMap 中有一個元素 key(5),我們再使用兩個線程:t1 添加元素 key(3),t2 添加元素 key(7),當元素 key(3) 和 key(7) 都添加到 HashMap 中之後,線程 t1 在執行到 Entry<K,V> next = e.next; 時,交出了 CPU 的使用權,源碼如下:
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry<K,V> e : table) {
while(null != e) {
Entry<K,V> next = e.next; // 線程一執行此處
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
}
}
}
那麼此時線程 t1 中的 e 指向了 key(3),而 next 指向了 key(7) ;之後線程 t2 重新 rehash 之後鏈表的順序被反轉,鏈表的位置變成了 key(5) → key(7) → key(3),其中 “→” 用來表示下一個元素。
當 t1 重新獲得執行權之後,先執行 newTalbe[i] = e 把 key(3) 的 next 設置爲 key(7),而下次循環時查詢到 key(7) 的 next 元素爲 key(3),於是就形成了 key(3) 和 key(7) 的循環引用,因此就導致了死循環的發生,如下圖所示:
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-kERZLCA4-1589017615100)(https://s0.lgstatic.com/i/image3/M01/73/D9/CgpOIF5rDYmAPR1lAABl-qSxBYs115.png)]
當然發生死循環的原因是 JDK 1.7 鏈表插入方式爲首部倒序插入,這個問題在 JDK 1.8 得到了改善,變成了尾部正序插入。
有人曾經把這個問題反饋給了 Sun 公司,但 Sun 公司認爲這不是一個問題,因爲 HashMap 本身就是非線程安全的,如果要在多線程下,建議使用 ConcurrentHashMap 替代,但這個問題在面試中被問到的機率依然很大,所以在這裏需要特別說明一下。