Java——HashMap原始碼解析
概述
雜湊表基於 Map
介面的實現。此實現提供了所有可選的對映操作,並且允許鍵為 null
,值也為 null
。HashMap 除了不支援同步操作以及支援 null
的鍵值外,其功能大致等同於 Hashtable。這個類不保證元素的順序,並且也不保證隨著時間的推移,元素的順序不會改變。
假設雜湊函式使得元素在雜湊桶中分佈均勻,那麼這個實現對於 put 和 get 等操作提供了常數時間的效能。
對於一個 HashMap 的例項,有兩個因子影響著其效能: 初始容量 和 負載因子 。容量就是雜湊表中雜湊桶的個數,初始容量就是雜湊表被初次建立時的容量大小。負載因子是在進行自動擴容之前衡量雜湊表儲存鍵值對的一個指標。當雜湊表中的鍵值對超過 capacity * loadfactor
時,就會進行 resize 的操作。
作為一般規則,預設負載因子(0.75)在時間和空間成本之間提供了良好的折衷。負載因子越大,空間開銷越小,但是查詢的開銷變大了。
注意,迭代器的快速失敗行為不能得到保證,一般來說,存在非同步的併發修改時,不可能作出任何堅決的保證。快速失敗迭代器盡最大努力丟擲 ConcurrentModificationException
異常。因此,編寫依賴於此異常的程式的做法是錯誤的,正確做法是:迭代器的快速失敗行為應該僅用於檢測程式錯誤。
原始碼分析
主要欄位
/** * 初始容量大小 —— 必須是2的冪次方 */ static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 /** * 最大容量 */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * 預設負載因子 */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * 當連結串列長度超過這個值時轉換為紅黑樹 */ static final int TREEIFY_THRESHOLD = 8; /** * The bin count threshold for untreeifying a (split) bin during a * resize operation. Should be less than TREEIFY_THRESHOLD, and at * most 6 to mesh with shrinkage detection under removal. */ static final int UNTREEIFY_THRESHOLD = 6; /** * The smallest table capacity for which bins may be treeified. * (Otherwise the table is resized if too many nodes in a bin.) * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts * between resizing and treeification thresholds. */ static final int MIN_TREEIFY_CAPACITY = 64; /** * table 在第一次使用時進行初始化並在需要的時候重新調整自身大小。對於 table 的大小必須是2的冪次方。 */ transient Node<K,V>[] table; /** * Holds cached entrySet(). Note that AbstractMap fields are used * for keySet() and values(). */ transient Set<Map.Entry<K,V>> entrySet; /** * 鍵值對的個數 */ transient int size; /** * HashMap 進行結構性調整的次數。結構性調整指的是增加或者刪除鍵值對等操作,注意對於更新某個鍵的值不是結構特性調整。 */ transient int modCount; /** * 所能容納的 key-value 對的極限(表的大小 capacity * load factor),達到這個容量時進行擴容操作。 */ int threshold; /** * 負載因子,預設值為 0.75 */ final float loadFactor;
從上面我們可以得知,HashMap中指定的雜湊桶陣列 table.length 必須是2的冪次方,這與常規性的把雜湊桶陣列設計為素數不一樣。指定為2的冪次方主要是在兩方面做優化:
- 擴容:擴容的時候,雜湊桶擴大為當前的兩倍,因此只需要進行左移操作
- 取模:由於雜湊桶的個數為2的冪次,因此可以用 & 操作來替代耗時的模運算,
n % table.length -> n & (table.length - 1)
雜湊函式
/** * 雜湊函式 */ static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
key 的雜湊值通過它自身 hashCode 的高十六位與低十六位進行亦或得到。這麼做得原因是因為,由於雜湊表的大小固定為 2 的冪次方,那麼某個 key 的 hashCode 值大於 table.length,其高位就不會參與到 hash 的計算(對於某個 key 其所在的桶的位置的計算為 hash & (table.length - 1)
)。因此通過 hashCode()
的高16位異或低16位實現的: (h = key.hashCode()) ^ (h >>> 16)
,主要是從速度、功效、質量來考慮的,保證了高位 Bits 也能參與到 Hash 的計算。
tableSizeFor函式
/** * 返回大於等於capacity的最小2的整數次冪 */ static final int tableSizeFor(int cap) { int n = cap - 1; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; }
根據註釋可以知道,這個函式返回大於或等於 cap 的最小二的整數次冪的值。比如對於3,返回4;對於10,返回16。詳解如下:
假設對於 n (32位數)其二進位制為 01xx...xx,
n >>> 1,進行無符號右移一位, 001xx..xx,位或得 011xx..xx
n >>> 2,進行無符號右移兩位, 00011xx..xx,位或得 01111xx..xx
依此類推,無符號右移四位再進行位或將得到8個1,無符號右移八位再進行位或將得到16個1,無符號右移十六位再進行位或將得到32個1。根據這個我們可以知道進行這麼多次無符號右移及位或操作,那麼可讓數 n 的二進位制位最高位為1的後面的二進位制位全部變成1。此時進行 +1 操作,即可得到最小二的整數次冪的值。(《高效程式的奧祕》第3章——2的冪界方 有對此進行進一步討論,可自行檢視)
回到上面的程式,之所以在開頭先進行一次 -1 操作,是為了防止傳入的 cap 本身就是二的冪次方,此時得到的就是下一個二的冪次方了,比如傳入4,那麼在不進行 -1 的情況下,將得到8。
建構函式
/** * 傳入指定的初始容量和負載因子 */ public HashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor; //返回2的冪次方 this.threshold = tableSizeFor(initialCapacity); }
對於上面的構造器,我們需要注意的是 this.threshold = tableSizeFor(initialCapacity);
這邊的 threshold 為 2的冪次方,而不是 capacity * load factor
,當然此處並非是錯誤,因為此時 table 並沒有真正的被初始化,初始化動作被延遲到了 putVal()
當中,所以 threshold 會被重新計算。
/** * 根據指定的容量以及預設負載因子(0.75)初始化一個空的 HashMap 例項 * * 如果 initCapacity是負數,那麼將丟擲 IllegalArgumentException */ public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } /** * 根據預設的容量和負載因子初始化一個空的 HashMap 例項 */ public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted } /** * Constructs a new <tt>HashMap</tt> with the same mappings as the * specified <tt>Map</tt>.The <tt>HashMap</tt> is created with * default load factor (0.75) and an initial capacity sufficient to * hold the mappings in the specified <tt>Map</tt>. * * @paramm the map whose mappings are to be placed in this map * @throwsNullPointerException if the specified map is null */ public HashMap(Map<? extends K, ? extends V> m) { this.loadFactor = DEFAULT_LOAD_FACTOR; putMapEntries(m, false); }
查詢
/** * 返回指定 key 所對應的 value 值,當不存在指定的 key 時,返回 null。 * * 當返回 null 的時候並不表明雜湊表中不存在這種關係的對映,有可能對於指定的 key,其對應的值就是 null。 * 因此可以通過 containsKey 來區分這兩種情況。 */ public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; } /** * 1.首先通過 key 的雜湊值找到其所在的雜湊桶 * 2.對於 key 所在的雜湊桶只有一個元素,此時就是 key 對應的節點, * 3.對於 key 所在的雜湊桶超過一個節點,此時分兩種情況: *如果這是一個 TreeNode,表明通過紅黑樹儲存,在紅黑樹中查詢 *如果不是一個 TreeNode,表明通過連結串列儲存(鏈地址法),在連結串列中查詢 * 4.查詢不到相應的 key,返回 null */ 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) { if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; }
儲存
/** * 在對映中,將指定的鍵與指定的值相關聯。如果對映關係之前已經有指定的鍵,那麼舊值就會被替換 */ public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } /** * * @param onlyIfAbsent if true, don't change existing value * * 1.判斷雜湊表 table 是否為空,是的話進行擴容操作 * 2.根據鍵 key 計算得到的 雜湊桶陣列索引,如果 table[i] 為空,那麼直接新建節點 * 3.判斷 table[i] 的首個元素是否等於 key,如果是的話就更新舊的 value 值 * 4.判斷 table[i] 是否為 TreeNode,是的話即為紅黑樹,直接在樹中進行插入 * 5.遍歷 table[i],遍歷過程發現 key 已經存在,更新舊的 value 值,否則進行插入操作,插入後發現連結串列長度大於8,則將連結串列轉換為紅黑樹 */ 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 為空,進行擴容操作 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; // tab[i] 為空,直接新建節點 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; //tab[i] 首個元素即為 key,更新舊值 if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; //當前節點為 TreeNode,在紅黑樹中進行插入 else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { //遍歷 tab[i],key 已經存在,更新舊的 value 值,否則進心插入操作,插入後連結串列長度大於8,將連結串列轉換為紅黑樹 for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); //連結串列長度大於8 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } // key 已經存在 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } //key 已經存在,更新舊值 if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } //HashMap插入元素表明進行了結構性調整 ++modCount; //實際鍵值對數量超過 threshold,進行擴容操作 if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
擴容
/** * 初始化或者對雜湊表進行擴容操作。如果當前雜湊表為空,則根據欄位閾值中的初始容量進行分配。 * 否則,因為我們擴容兩倍,那麼對於桶中的元素要麼在原位置,要麼在原位置再移動2次冪的位置。 */ 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; } //容量沒有超過最大值,容量變為原來兩倍 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 //呼叫了HashMap的帶參構造器,初始容量用threshold替換, //在帶參構造器中,threshold的值為 tableSizeFor() 的返回值,也就是2的冪次方,而不是 capacity * load factor newCap = oldThr; else {// zero initial threshold signifies using defaults //初次初始化,容量和閾值使用預設值 newCap = DEFAULT_INITIAL_CAPACITY; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } 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 = newTab; if (oldTab != null) { for (int j = 0; j < oldCap; ++j) { Node<K,V> e; if ((e = oldTab[j]) != null) { //將原雜湊桶置空,以便GC oldTab[j] = null; //當前節點不是以連結串列形式存在,直接計算其應放置的新位置 if (e.next == null) newTab[e.hash & (newCap - 1)] = e; //當前節點是TreeNode else if (e instanceof TreeNode) ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { // preserve order //節點以連結串列形式儲存 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; } if (hiTail != null) { hiTail.next = null; newTab[j + oldCap] = hiHead; } } } } } return newTab; }
因為雜湊表使用2次冪的拓展(指長度拓展為原來的2倍),所以在擴容的時候,元素的位置要麼在原位置,要麼在原位置再移動2次冪的位置。為什麼是這麼一個規律呢?我們假設 n 為 table 的長度,圖(a)表示擴容前的key1和key2兩種key確定索引位置的示例,圖(b)表示擴容後key1和key2兩種key確定索引位置的示例,其中hash1是key1對應的雜湊與高位運算結果。

元素在重新計算hash之後,因為n變為2倍,那麼n-1的mask範圍在高位多1bit(紅色),因此新的index就會發生這樣的變化:

因此,我們在擴容的時候,只需要看看原來的hash值新增的那個 bit 是1還是0就好了,是0的話索引沒變,是1的話索引變成“原索引+oldCap”,可以看看下圖為16擴充為32的resize示意圖:

刪除
/** * 刪除指定的 key 的對映關係 */ public V remove(Object key) { Node<K,V> e; return (e = removeNode(hash(key), key, null, false, true)) == null ? null : e.value; } /**Java * * 1.根據 key 的雜湊值在雜湊桶中查詢是否存在這個包含有這個 key 的節點 *連結串列頭節點是要查詢的節點 *節點是TreeNode,在紅黑樹中查詢 *在連結串列中進行查詢 * 2.如果查詢到對應的節點,進行刪除操作 *從紅黑樹中刪除 *將連結串列頭節點刪除 *在連結串列中刪除 * * @param hash key 的 hash 值 * @param key 指定的 key * @param value 當 matchhValue 為真時,則要匹配這個 value * @param matchValue 為真並且與 value 相等時進行刪除 * @param movable if false do not move other nodes while removing * @return the node, or null if none */ final Node<K,V> removeNode(int hash, Object key, Object value, boolean matchValue, boolean movable) { Node<K,V>[] tab; Node<K,V> p; int n, index; if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) { Node<K,V> node = null, e; K k; V v; //連結串列頭即為要刪除的節點 if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) node = p; else if ((e = p.next) != null) { //節點為TreeNode,在紅黑樹中查詢是否存在指定的key if (p instanceof TreeNode) node = ((TreeNode<K,V>)p).getTreeNode(hash, key); else { //在連結串列中查詢是否存在指定的key do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { node = e; break; } p = e; } while ((e = e.next) != null); } } if (node != null && (!matchValue || (v = node.value) == value || (value != null && value.equals(v)))) { //從紅黑樹中刪除 if (node instanceof TreeNode) ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable); //連結串列頭刪除 else if (node == p) tab[index] = node.next; //連結串列中的元素刪除 else p.next = node.next; //進行結構特性調整 ++modCount; --size; afterNodeRemoval(node); return node; } } return null; } /** * 刪除所有的對映關係 */ public void clear() { Node<K,V>[] tab; modCount++; if ((tab = table) != null && size > 0) { size = 0; for (int i = 0; i < tab.length; ++i) //置 null 以便 GC tab[i] = null; } }
問題
new HashMap(18)
參考資料
ofollow,noindex" target="_blank">Java 8系列之重新認識HashMap