説明
本文基於 jdk 8 編寫。
HashMap 的結構
- 圖中的數組是 table 屬性,hashMap 基礎的屬性。一個數組,用於承載 node,table 的每一個格被稱為桶。
- node 是 hashMap 中基礎的 node 節點,用於存儲 key, value。
- 桶位置計算的公式是
(n - 1) & hash,n 指 table 的長度,hash 指 key 的 hash 值。 - 桶位置計算時有可能出現 hash 衝突的現象,在 jdk 1.7 及之前採用的是把 node 拼接成鏈表的方式。但如果 hash 衝突嚴重,桶位置上的鏈表會很長,影響查詢性能。從 jdk 1.8 開始,改成了鏈表 + 紅黑樹的方式,在一個桶位置上元素很多的情況下,樹的查詢效率優於鏈表。
關鍵屬性
table
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*
* hashMap 基礎的屬性。一個數組,用於承載 node,table 的每一個格被稱為桶
*/
transient Node<K,V>[] table;
Node
/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*
* hashMap 中基礎的 node 節點,用於存儲 key, value
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
}
modCount
這個屬性與理解 HashMap 的核心流程無關,如果讀者只關心核心流程,可以不用關注。
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*
* 用於記錄修改次數,每次增刪改時會維護它的值
* 在一個迭代器開始的時候,會把 modCount 用一個局部變量 mc 記錄下來。迭代器遍歷完成後,如果發現 modCount 和 mc 不相同,説明迭代期間 hashMap 進行過修改,則拋出異常。
* 關於迭代器遍歷,可以看一下 EntrySet 內部類的 forEach 方法
*/
transient int modCount;
關於迭代器遍歷,可以看一下 EntrySet 內部類的 forEach 方法。
/**
* 請注意,源碼裏 EntrySet 的其他成員屬性和成員方法,這裏不作展示
*/
final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
// 把 modCount 用一個局部變量 mc 記錄下來
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e);
}
// 迭代器遍歷完成後,如果發現 modCount 和 mc 不相同,説明迭代期間 hashMap 進行過修改,則拋出異常。
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
threshold 擴容閾值
/**
* The next size value at which to resize (capacity * load factor).
*
* 擴容閾值,由 capacity * loadFactor 得到。決定何時 hashMap 執行 resize 方法擴容
*
* @serial
*/
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
int threshold;
loadFactor 加載因子
/**
* The load factor for the hash table.
*
* 加載因子,決定了 hashMap 實際能存儲的元素容量
*
* @serial
*/
final float loadFactor;
/**
* The load factor used when none specified in constructor.
*
* 默認的 loadFactor 加載因子
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
加載因子是表示 HashMap 中元素的填滿的程度。加載因子的目的是,為了降低 HashMap 中的 hash 衝突機率,防止大量 node 都因為 hash 衝突變成了鏈表或樹,同時平衡佔用的空間開銷。
加載因子越大,填滿的元素越多。優點是,空間利用率高了。缺點是,hash 衝突的機會加大了。
加載因子越小,填滿的元素越少。優點是,衝突的機會減小了。缺點是,空間浪費多了。
默認的加載因子 DEFAULT_LOAD_FACTOR = 0.75f 算是在 hash 衝突機率與空間開銷間做了取捨平衡。
構造方法
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and the default load factor (0.75).
*
* @param initialCapacity the initial capacity. 初始容量,由 capacity * loadFactor 可以得到擴容閾值 threshold
* @throws IllegalArgumentException if the initial capacity is negative.
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
我們可以注意到,HashMap 裏並沒有 capacity 這個屬性,我們在構造方法中傳入的 capacity,其實會經過 capacity * loadFactor 計算,得到擴容閾值 threshold。
put 方法
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* put 方法,調用 Val 給指定的 key 添加對應的 value
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
// 第一個 boolean false 表示:當要 put 的 key 在 hashMap 中已存在時,會直接覆蓋原有 value。第二個 boolean true 不用關心,與主流程無關。
return putVal(hash(key), key, value, false, true);
}
putVal
/**
* Implements Map.put and related methods.
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value 如果目標 key 在 hashMap 中已經存在,則不會覆蓋原有的 value
* @param evict if false, the table is in creation mode. 不用關心,與主流程無關
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 如果 table 還沒有初始化,則初始化 table
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 桶位置計算公式: (n - 1) & hash。如果定位到的桶位置為空,則把 node 插入桶位置。p 指向桶位置
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
// 桶位置不為空,説明出現 hash 碰撞,走 else 分支
else {
Node<K,V> e; K k;
// 通過 key 的 hash 值和 equals 方法判斷桶位置上的 key 是否相同。如果相同則用 e 指向這個節點
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 判斷桶位置上是否是一棵樹,如果是一棵樹,則調用樹添加元素的方法,然後用 e 指向樹上的這個節點
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// 不是樹,則説明是鏈表
else {
// 迭代鏈表,binCount 是鏈表長度計數
for (int binCount = 0; ; ++binCount) {
// 用 e 指向本次迭代的當前元素。如果本次迭代,當前元素為空,即到達了鏈表的尾部
if ((e = p.next) == null) {
// 向鏈表尾部追加 node
p.next = newNode(hash, key, value, null);
// 如果鏈表長度達到了閾值,把鏈表轉換成樹。鏈表轉換樹的閾值無法修改,因為是 final 修飾的。
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 通過 key 的 hash 值和 equals 方法判斷本次迭代的 key 是否相同。如果相同則用 e 指向這個節點。然後停止迭代鏈表。
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
// 維護當前元素,準備下一次迭代
p = e;
}
}
// 如果 e 不為空,説明要添加的 key 原先已存在於這個桶位置上,覆蓋原有 value。這裏體現了 hashMap 的 onlyIfAbsent 選項為 false 時,出現 key 相同時,會直接覆蓋原有 value
if (e != null) { // existing mapping for key
V oldValue = e.value;
// onlyIfAbsent 選項為 false 時,或原有 value 為 null 時,會直接覆蓋原有 value
if (!onlyIfAbsent || oldValue == null)
e.value = value;
// 這個方法不用關心。留給 LinkedHashMap 回調用。
afterNodeAccess(e);
// 返回原有的 value
return oldValue;
}
}
// 維護修改次數計數
++modCount;
// 如果達到了擴容閾值,則 resize
if (++size > threshold)
resize();
// 這個方法不用關心。留給 LinkedHashMap 回調用。
afterNodeInsertion(evict);
// 沒有找到 key 對應的 value,返回 null
return null;
}
有一個細節,鏈表轉換樹的閾值 TREEIFY_THRESHOLD 無法修改,因為是 final 修飾的,之前面試被問到過。
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*
* 鏈表轉換樹的閾值,無法修改,因為是 final 修飾的
*/
static final int TREEIFY_THRESHOLD = 8;
get 方法
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>A return value of {@code null} does not <i>necessarily</i>
* indicate that the map contains no mapping for the key; it's also
* possible that the map explicitly maps the key to {@code null}.
* The {@link #containsKey containsKey} operation may be used to
* distinguish these two cases.
*
* @see #put(Object, Object)
*/
public V get(Object key) {
Node<K,V> e;
// 根據指定的 key 查找 node,返回 node 的 value
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
getNode
/**
* Implements Map.get and related methods.
*
* 根據指定的 key,查找 node
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
// 如果 table 不為空,且根據 key 對應到的桶位置不為空
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 通過 key 的 hash 值和 equals 方法判斷桶位置上的 key 是否相同
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
// 和目標 key 相同,返回當前節點
return first;
// 桶位置不為空,説明可能存在 hash 碰撞,判斷桶位置上的元素是否有下一個節點
if ((e = first.next) != null) {
// 判斷桶位置上是否是一棵樹,如果是一棵樹,則調用樹查找元素的方法
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
// 不是樹,則説明是鏈表,迭代鏈表
do {
// 通過 key 的 hash 值和 equals 方法判斷本次迭代的 key 是否相同
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
// 和目標 key 相同,返回當前節點
return e;
} while ((e = e.next) != null);
}
}
// 沒有找到 key 對應的元素,返回 null
return null;
}
resize 方法
常見的執行 resize() 方法的兩種情況
在 HashMap 的 putVal 方法中,如果 table 未初始化,則會執行resize(),然後就初始化table。初始化 table 由 resize 負責。
// 如果 table 還沒有初始化,則初始化 table
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
在 HashMap 的 putVal 方法中,存儲的數據量大於 threshold 時,會執行 resize() 方法。
// 如果 hashMap 中的元素數量達到了擴容閾值,則 resize
if (++size > threshold)
resize();
在putVal()方法中,size表示當前HashMap的數據量,如果size大於threshold,則會執行該方法,進行擴容操作。
resize 方法源碼
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* 初始化 hashMap 或給 hashMap 的 table 擴容兩倍
*
* @return the table
*/
final Node<K,V>[] resize() {
// oldTab 指向舊 table
Node<K,V>[] oldTab = table;
// 舊 table 的長度
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// oldThr 表示舊的擴容閾值 threshold。threshold = 數組長度 * 負載因子
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
// 當舊 table 的長度大於最大容量時的處理
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 如果舊的數組長度 * 2 後小於 int 的最大值,並且舊的數組長度大於 16
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
// 擴容閾值 * 2
newThr = oldThr << 1; // double threshold
}
// 如果舊的 threshold 大於 0,初始容量設置為舊的 threshold。這裏在 table 初始化時會用到
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
// 擴容閾值為 0 表示使用默認值,DEFAULT_INITIAL_CAPACITY = 16,DEFAULT_LOAD_FACTOR = 0.75,因此默認的擴容閾值為 12
else { // zero initial threshold signifies using defaults
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 屬性
threshold = newThr;
// 不用關心這個註解。這個註解在屏蔽一些無關緊要的警告,使開發者能看到一些他們真正關心的警告,降低開發者的心智負擔。
// 創建一個新的 table,供擴容後使用
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
// 把新 table 賦值給 hashMap 的屬性
table = newTab;
// 如果舊 table 不為空,開始擴容
if (oldTab != null) {
// 迭代遍歷舊 table
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
// e 指向當前桶位置的元 node,當前桶位置的 node 不為空時
if ((e = oldTab[j]) != null) {
// 清空舊 table 的當前桶位置
oldTab[j] = null;
if (e.next == null)
// 如果當前桶位置的 node 不是鏈表不是紅黑樹,則根據桶位置計算公式,重新分配 node 的桶位置
newTab[e.hash & (newCap - 1)] = e;
// 如果當前桶位置的 node 是樹,則使用樹的方式,把舊樹上的 node,重新分配到新的樹中
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
// 不是樹,則是鏈表
else { // preserve order
// 把鏈表中的所有節點分成兩條鏈表
// 一條鏈表的 node 是不需要更換 table 下標的
Node<K,V> loHead = null, loTail = null;
// 一條鏈表的 node 是需要更換 table 下標的
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
// 迭代遍歷鏈表
do {
next = e.next;
// 如果 e.hash & oldCap 進行二進制與運算,算出的結果為 0,即説明該 node 所對應的數組下標不需要改變。把該 node 追加到 loHead 鏈表上
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
// 否則説明該 node 所對應的數組下標需要改變。把該 node 追加到 hiHead 鏈表上
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
// 如果不需要更換 table 下標的 node 鏈表 -- loTail 不為空,則把 loTail 放在當前桶位置上
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
// 如果需要更換 table 下標的 node 鏈表 -- hiTail 不為空,則把 hiTail 放到新的桶位置上。並且計算公式是把當前 table 下標直接 + 舊 table 的長度
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
// 返回新創建的 table
return newTab;
}
兩個個公式
(e.hash & oldCap) == 0 判斷是否需要重新分配桶位置
e 是當前 node,oldCap 是舊數組的長度。這個公式算出的結果為 0,説明該 node (即 e)所對應的數組下標不需要改變。結果不為 0,説明該 node 所對應的數組下標需要改變。
(e.hash & oldCap) == 0 為什麼能判斷出是否需要重新分配桶位置?
這個公式是推導出來的,推導過程是數學,我們不需要關注。如果想了解此公式的推導請見:HashMap擴容時的rehash方法中(e.hash & oldCap) == 0算法推導
j + oldCap 桶位置重分配公式
j 是 node 的舊桶位置,oldCap 是舊 table 的長度。即 舊桶位置 + 舊 table 的長度。得到這個公式的運算結果,是擴容後該元素的新桶位置。可以理解為是桶位置重新分配的公式。
為什麼這樣能得到呢?我們來舉例回答一下。
現在我們有一個 node key 的 hash 值是 9,對應的二進制位。舊 table 的長度 oldCap 是 8,新 table 的長度 newCap 是 16。以下是手寫演算驗證:
為什麼 HashMap 擴容是 2 倍?
通過本文桶位置重新分配的公式 j + oldCap 手寫驗證,我們可以看出,當 HashMap 擴容兩倍的時候,剛好可以用到 桶位置重新分配的公式 j + oldCap,加快計算重分配後的桶位置。同時,newCap = oldCap << 1 新 table 長度 = 舊 table 長度在二進制上左移一位,這樣的位運算也很高效。
其實這裏擴容倍數和桶位置重分配公式的配合,能體現出作者縝密的思考和深厚的數學功底。