秒殺Java面試官——集合篇(二)node
3、HashMap底層實現原理(基於JDK1.8)面試
面試中,你是否也曾被問過如下問題呢:算法
你知道HashMap的數據結構嗎?HashMap是如何實現存儲的?底層採用了什麼算法?爲何採用這種算法?如何對HashMap進行優化?若是HashMap的大小超過了負載因子定義的容量,怎麼辦?等等。數組
有以爲很難嗎?別怕!下面博主就帶着你們深度剖析,以源代碼爲依據,逐一分析,看看HashMap究竟是怎麼玩的:數據結構
① HashMap源碼片斷 —— 整體介紹: app
/* Hash table based implementation of the <tt>Map</tt> interface(HashMap實現了Map接口). This implementation provides all of the optional map operations, and permits <tt>null</tt> values and the <tt>null</tt> key(容許儲存null值和null鍵). (The <tt>HashMap</tt> class is roughly equivalent to <tt>Hashtable</tt>, except that it is unsynchronized and permits nulls.(HashTable和HashMap很類似,除了HashTable的方法是同步的,而且不容許儲存null值和null鍵)) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time(HashMap不保證映射的順序,特別是它不保證該順序不隨時間變化).*/ide
② HashMap源碼片斷 —— 六大初始化參數:函數
/** * 初始容量1 << 4 = 16 */ static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; /** * 最大容量1 << 30 = 1073741824 */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * 默認負載因子0.75f */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * 由鏈表轉換成樹的閾值:即當bucket(桶)中bin(箱子)的數量超過 * TREEIFY_THRESHOLD時使用樹來代替鏈表。默認值是8 */ static final int TREEIFY_THRESHOLD = 8; /** * 由樹轉換成鏈表的閾值:當執行resize操做時,當bucket中bin的數量少於此值, * 時使用鏈表來代替樹。默認值是6 */ static final int UNTREEIFY_THRESHOLD = 6; /** * 樹的最小容量 */ static final int MIN_TREEIFY_CAPACITY = 64;
③ HashMap源碼片斷 —— 內部結構:優化
/** * Basic hash bin node, used for most entries. */ // Node是單向鏈表,它實現了Map.Entry接口 static class Node<K,V> implements Map.Entry<K,V> { final int hash; // 鍵對應的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; } // 存儲(位桶)的數組</k,v> transient Node<K,V>[] table; // 紅黑樹 static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> { TreeNode<K,V> parent; // 父節點 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); }
簡單看:在JDK1.8中,HashMap採用位桶+鏈表+紅黑樹實現。具體實現原理,咱們繼續看源碼。關於紅黑樹,我將在後期《算法篇》詳細介紹。ui
④ HashMap源碼片斷 —— 數組Node[]位置:
// 第一步:先計算key對應的Hash值 static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }// 第二步:保證哈希表散列均勻 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; }對第二步的做用,進行簡要說明(很高級!):
{ 能夠從源碼看出,在HashMap的構造函數中,都直接或間接的調用了tableSizeFor函數。下面分析緣由:length爲2的整數冪保證了length-1最後一位(固然是二進制表示)爲1,從而保證了取索引操做 h&(length-1)的最後一位同時有爲0和爲1的可能性,保證了散列的均勻性。反過來說,當length爲奇數時,length-1最後一位爲0,這樣與h按位與的最後一位確定爲0,即索引位置確定是偶數,這樣數組的奇數位置所有沒有放置元素,浪費了大量空間。簡而言之:length爲2的冪保證了按位與最後一位的有效性,使哈希表散列更均勻。}
// 第三步:計算索引:index = (tab.length - 1) & hash if (tab == null || (n = tab.length) == 0) return; int index = (n - 1) & hash;(區別於HashTable :index = (hash & 0x7FFFFFFF) % tab.length;
取模中的除法運算效率很低,可是HashMap的位運算效率很高)
⑤ HashMap源碼片斷 —— 經常使用get()/put()操做:
/** * Implements Map.get and related methods * * @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; if ((tab = table) != null && (n = tab.length) > 0 && //tab[(n - 1) & hash]獲得對象的保存位 (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) { //判斷:若是第一個節點是TreeNode,則採用紅黑樹處理衝突 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; } /** * 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 * @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; if ((tab = table) == null || (n = tab.length) == 0) //若是tab爲空或長度爲0,則分配內存resize() n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null) //tab[i = (n - 1) & hash]找到put位置,若是爲空,則直接put tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; //先判斷key的hash()方法判斷,再調用equals()方法判斷 if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; else if (p instanceof TreeNode) //屬於紅黑樹處理衝突 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { //鏈表處理衝突 for (int binCount = 0; ; ++binCount) { //p第一次指向表頭,以後依次後移 if ((e = p.next) == null) { //e爲空,表示已到表尾也沒有找到key值相同節點,則新建節點 p.next = newNode(hash, key, value, null); //新增節點後若是節點個數到達閾值,則將鏈表轉換爲紅黑樹 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } //容許存儲null鍵null值 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; //指針下移一位 p = e; } } //更新hash值和key值均相同的節點Value值 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; }
⑥ HashMap源碼片斷 —— 擴容resize():
//可用來初始化HashMap大小 或從新調整HashMap大小 變爲原來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; // 擴容閾值加倍 } else if (oldThr > 0) // oldCap=0 ,oldThr>0此時newThr=0 newCap = oldThr; else { // oldCap=0,oldThr=0 至關於使用默認填充比和初始容量 初始化 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) { 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 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; }
看完以上源碼,是否感受身體被掏空了?別慌,博主如今以一個簡單的小例子爲主導,帶領你們從新梳理一下。
簡析底層實現過程:
①建立HashMap,初始容量爲16,實際容量 = 初始容量*負載因子(默認0.75) = 12;
②調用put方法,會先計算key的hash值:hash = key.hashCode()。
③調用tableSizeFor()方法,保證哈希表散列均勻。
④計算Nodes[index]的索引:先進行index = (tab.length - 1) & hash。
⑤若是索引位爲null,直接建立新節點,若是不爲null,再判斷所由於上是否有元素
⑥若是有:則先調用hash()方法判斷,再調用equals()方法進行判斷,若是都相同則直接用新的Value覆蓋舊的;
⑦若是不一樣,再判斷第一個節點類型是否爲樹節點(涉及到:鏈表轉換成樹的閾值,默認8),若是是,則按照紅黑樹的算法進行存儲;若是不是,則按照鏈表存儲;
⑧當存儲元素過多時,須要進行擴容:
默認的負載因子是0.75,若是實際元素所佔容量佔分配容量的75%時就要擴容了。大約變爲原來的2倍(newThr =oldThr << 1);