面試必問:HashMap 底層實現原理
HashMap是在面試中經常會問的一點,很多時候我們僅僅只是知道HashMap他是允許鍵值對都是Null,並且是非執行緒安全的,如果在多執行緒的環境下使用,是很容易出現問題的。 這是我們通常在面試中會說的,但是有時候問到底層的原始碼分析的時候,為什麼允許為Null,為什麼不安全,這些問題的時候,如果沒有分析過原始碼的話,好像很難回答, 這樣的話我們來研究一下這個原始碼。看看原因吧。
HashMap最早出現在JDK1.2中,它的底層是基於的雜湊演算法。允許鍵值對都是Null,並且是非執行緒安全的,我們先看看這個1.8版本的JDK中HashMap的資料結構吧。
HashMap圖解如下

我們都知道HashMap是陣列+連結串列組成的,bucket陣列是HashMap的主體,而連結串列是為了解決雜湊衝突而存在的,但是很多人不知道其實HashMap是包含樹結構的,但是得有一點 注意事項,什麼時候會出現紅黑樹這種紅樹結構的呢?我們就得看原始碼了,原始碼解釋說預設連結串列長度大於8的時候會轉換為樹。我們看看原始碼說的
結構
/** * Basic hash bin node, used for most entries.(See below for * TreeNode subclass, and in LinkedHashMap for its Entry subclass.) */ /** Node是hash基礎的節點,是單向連結串列,實現了Map.Entry介面 */ 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; } }
接下來就是樹結構了
TreeNode 是紅黑樹的資料結構。
/** * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn * extends Node) so can be used as extension of either regular or * linked node. */ static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> { TreeNode<K,V> parent;// red-black tree links TreeNode<K,V> left; TreeNode<K,V> right; TreeNode<K,V> prev;// needed to unlink next upon deletion boolean red; TreeNode(int hash, K key, V val, Node<K,V> next) { super(hash, key, val, next); } /** * Returns root of tree containing this node. */ final TreeNode<K,V> root() { for (TreeNode<K,V> r = this, p;;) { if ((p = r.parent) == null) return r; r = p; } }
我們在看一下類的定義
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
繼承了抽象的map,實現了Map介面,並且進行了序列化。
在類裡還有基礎的變數
變數
/** * The default initial capacity - MUST be a power of two. *預設初始容量 16 - 必須是2的冪 */ static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 /** * The maximum capacity, used if a higher value is implicitly specified * by either of the constructors with arguments. * MUST be a power of two <= 1<<30. * 最大容量 2的30次方 */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * The load factor used when none specified in constructor. * 預設載入因子,用來計算threshold */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * 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. * 連結串列轉成樹的閾值,當桶中連結串列長度大於8時轉成樹 * threshold = capacity * loadFactor */ 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. * 進行resize操作時,若桶中數量少於6則從樹轉成連結串列 */ 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. * 桶中結構轉化為紅黑樹對應的table的最小大小 * 當需要將解決 hash 衝突的連結串列轉變為紅黑樹時, * 需要判斷下此時陣列容量, * 若是由於陣列容量太小(小於 MIN_TREEIFY_CAPACITY ) * 導致的 hash 衝突太多,則不進行連結串列轉變為紅黑樹操作, * 轉為利用 resize() 函式對 hashMap 擴容 */ static final int MIN_TREEIFY_CAPACITY = 64; /** * 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.) * 儲存Node<K,V>節點的陣列 * 該表在首次使用時初始化,並根據需要調整大小。 分配時, * 長度始終是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; /** * The number of key-value mappings contained in this map. * 記錄 hashMap 當前儲存的元素的數量 */ transient int size; /** * 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). * 每次更改map結構的計數器 */ transient int modCount; /** * The next size value at which to resize (capacity * load factor). * 臨界值 當實際大小(容量*填充因子)超過臨界值時,會進行擴容 * @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; /** * The load factor for the hash table. * 負載因子:要調整大小的下一個大小值(容量*載入因子)。 * @serial */ final float loadFactor;
我們再看看構造方法
構造方法
/** * Constructs an empty <tt>HashMap</tt> with the specified initial * capacity and the default load factor (0.75). * * @paraminitialCapacity the initial capacity. * @throws IllegalArgumentException if the initial capacity is negative. * 傳入初始容量大小,使用預設負載因子值 來初始化HashMap物件 */ public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } /** * Constructs an empty <tt>HashMap</tt> with the default initial capacity * (16) and the default load factor (0.75). * 預設容量和負載因子 */ public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted } /** * Constructs an empty <tt>HashMap</tt> with the specified initial * capacity and load factor. * * @paraminitialCapacity the initial capacity * @paramloadFactorthe load factor * @throws IllegalArgumentException if the initial capacity is negative *or the load factor is nonpositive * 傳入初始容量大小和負載因子 來初始化HashMap物件 */ public HashMap(int initialCapacity, float loadFactor) { // 初始容量不能小於0,否則報錯 if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); // 初始容量不能大於最大值,否則為最大值 if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; //負載因子不能小於或等於0,不能為非數字 if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); // 初始化負載因子 this.loadFactor = loadFactor; // 初始化threshold大小 this.threshold = tableSizeFor(initialCapacity); } /** * Returns a power of two size for the given target capacity. * 找到大於或等於 cap 的最小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; }
在這原始碼中,loadFactor負載因子是一個非常重要的引數,因為他能夠反映HashMap桶陣列的使用情況, 這樣的話,HashMap的時間複雜度就會出現不同的改變。
當這個負載因子屬於低負載因子的時候,HashMap所能夠容納的鍵值對數量就是偏少的,擴容後,重新將鍵值對 儲存在桶陣列中,鍵與鍵之間產生的碰撞會下降,連結串列的長度也會隨之變短。
但是如果增加負載因子當這個負載因子大於1的時候,HashMap所能夠容納的鍵值對就會變多,這樣碰撞就會增加, 這樣的話連結串列的長度也會增加,一般情況下負載因子我們都不會去修改。都是預設的0.75。
擴容機制
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. * * @return the table */ final Node<K,V>[] resize() { //引用擴容前的Entry陣列 Node<K,V>[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length; int oldThr = threshold; int newCap, newThr = 0; if (oldCap > 0) { // 擴容前的陣列大小如果已經達到最大(2^30)了 //在這裡去判斷是否達到最大的大小 if (oldCap >= MAXIMUM_CAPACITY) { //修改閾值為int的最大值(2^31-1),這樣以後就不會擴容了 threshold = Integer.MAX_VALUE; return oldTab; } // 如果擴容後小於最大值 而且 舊陣列桶大於初始容量16, 閾值左移1(擴大2倍) else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold } // 如果陣列桶容量<=0 且 舊閾值 >0 else if (oldThr > 0) // initial capacity was placed in threshold //新的容量就等於舊的閥值 newCap = oldThr; else {// zero initial threshold signifies using defaults // 如果陣列桶容量<=0 且 舊閾值 <=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 = newTab; // 如果舊陣列桶不是空,則遍歷桶陣列,並將鍵值對對映到新的桶陣列中 //在這裡還有一點詭異的,1.7是不存在後邊紅黑樹的,但是1.8就是有紅黑樹 if (oldTab != null) { 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 // 如果不是紅黑樹,那也就是說他連結串列長度沒有超過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; } 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; }
所以說在經過resize這個方法之後,元素的位置要麼就是在原來的位置,要麼就是在原來的位置移動2次冪的位置上。 原始碼上的註釋也是可以翻譯出來的
/** * 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. * * @return the table 如果為null,則分配符合欄位閾值中儲存的初始容量目標。 否則,因為我們使用的是2次冪擴充套件, 所以每個bin中的元素必須保持相同的索引,或者在新表中以2的偏移量移動。 */ final Node<K,V>[] resize() .....
所以說他的擴容其實很有意思,就有了三種不同的擴容方式了,
在HashMap剛初始化的時候,使用預設的構造初始化,會返回一個空的table,並且 thershold為0,因此第一次擴容的時候預設值就會是16. 同時再去計算thershold = DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY = 16*0.75 = 12.
如果說指定初始容量的初始HashMap的時候,那麼這時候計算這個threshold的時候就變成了 threshold = DEFAULT_LOAD_FACTOR * threshold(當前的容量)
如果HashMap不是第一次擴容,已經擴容過了,那麼每次table的容量
threshold也會變成原來的2倍。
之前看1.7的原始碼的時候,是沒有這個紅黑樹的,而是在1.8 之後做了相應的優化。 使用的是2次冪的擴充套件(指長度擴為原來2倍)。 而且在擴充HashMap的時候,不需要像JDK1.7的實現那樣重新計算hash,這樣子他就剩下了計算hash的時間了。