秒殺Java面試官——集合篇(二)
三、HashMap底層實(shí)現(xiàn)原理(基于JDK1.8)
面試中,你是否也曾被問過以下問題呢:
你知道HashMap的數(shù)據(jù)結(jié)構(gòu)嗎?HashMap是如何實(shí)現(xiàn)存儲的?底層采用了什么算法?為什么采用這種算法?如何對HashMap進(jìn)行優(yōu)化?如果HashMap的大小超過了負(fù)載因子定義的容量,怎么辦?等等。
有覺得很難嗎?別怕!下面博主就帶著大家深度剖析,以源代碼為依據(jù),逐一分析,看看HashMap到底是怎么玩的:
① HashMap源碼片段 —— 總體介紹:
/* Hash table based implementation of the<tt>Map</tt> interface(HashMap實(shí)現(xiàn)了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不保證映射的順序,特別是它不保證該順序不隨時間變化).*/
② HashMap源碼片段 —— 六大初始化參數(shù):
- /**
- * 初始容量1 << 4 = 16
- */
- static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
- /**
- * 最大容量1 << 30 = 1073741824
- */
- static final int MAXIMUM_CAPACITY = 1 << 30;
- /**
- * 默認(rèn)負(fù)載因子0.75f
- */
- static final float DEFAULT_LOAD_FACTOR = 0.75f;
- /**
- * 由鏈表轉(zhuǎn)換成樹的閾值:即當(dāng)bucket(桶)中bin(箱子)的數(shù)量超過
- * TREEIFY_THRESHOLD時使用樹來代替鏈表。默認(rèn)值是8
- */
- static final int TREEIFY_THRESHOLD = 8;
- /**
- * 由樹轉(zhuǎn)換成鏈表的閾值:當(dāng)執(zhí)行resize操作時,當(dāng)bucket中bin的數(shù)量少于此值,
- * 時使用鏈表來代替樹。默認(rèn)值是6
- */
- static final int UNTREEIFY_THRESHOLD = 6;
- /**
- * 樹的最小容量
- */
- static final int MIN_TREEIFY_CAPACITY = 64;
③ HashMap源碼片段 —— 內(nèi)部結(jié)構(gòu):
- /**
- * Basic hash bin node, used for most entries.
- */
- // Node是單向鏈表,它實(shí)現(xiàn)了Map.Entry接口
- static class Node<K,V> implements Map.Entry<K,V> {
- final int hash; // 鍵對應(yīng)的Hash值
- final K key; // 鍵
- V value; // 值
- Node<K,V> next; // 下一個節(jié)點(diǎn)
- // 構(gòu)造函數(shù)
- Node(int hash, K key, V value, Node<K,V> next) {
- this.hash = hash;
- this.key = key;
- this.value = value;
- this.next = next;
- }
- // 存儲(位桶)的數(shù)組</k,v>
- sient Node<K,V>[] table;
- // 紅黑樹
- static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
- TreeNode<K,V> parent; // 父節(jié)點(diǎn)
- TreeNode<K,V> left; // 左節(jié)點(diǎn)
- TreeNode<K,V> right; // 右節(jié)點(diǎn)
- 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采用位桶+鏈表+紅黑樹實(shí)現(xiàn)。具體實(shí)現(xiàn)原理,我們繼續(xù)看源碼。關(guān)于紅黑樹,我將在后期《算法篇》詳細(xì)介紹。
④ HashMap源碼片段 —— 數(shù)組Node[]位置:
- // 第一步:先計算key對應(yīng)的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;
- }
★對第二步的作用,進(jìn)行簡要說明(很高級?。?/span>
{ 可以從源碼看出,在HashMap的構(gòu)造函數(shù)中,都直接或間接的調(diào)用了tableSizeFor函數(shù)。下面分析原因:length為2的整數(shù)冪保證了length-1最后一位(當(dāng)然是二進(jìn)制表示)為1,從而保證了取索引操作h&(length-1)的最后一位同時有為0和為1的可能性,保證了散列的均勻性。反過來講,當(dāng)length為奇數(shù)時,length-1最后一位為0,這樣與h按位與的最后一位肯定為0,即索引位置肯定是偶數(shù),這樣數(shù)組的奇數(shù)位置全部沒有放置元素,浪費(fèi)了大量空間。簡而言之:length為2的冪保證了按位與最后一位的有效性,使哈希表散列更均勻。}
- // 第三步:計算索引:index = (tab.length - 1) & hash
- if (tab == null || (n = tab.length) == 0) return;
- int index = (n - 1) & hash;
(區(qū)別于HashTable :index = (hash &0x7FFFFFFF) % tab.length;
取模中的除法運(yùn)算效率很低,但是HashMap的位運(yùn)算效率很高)
⑤ 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) {
- //判斷:如果第一個節(jié)點(diǎn)是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,則分配內(nèi)存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()方法判斷,再調(diào)用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值相同節(jié)點(diǎn),則新建節(jié)點(diǎn)
- p.next = newNode(hash, key, value, null);
- //新增節(jié)點(diǎn)后如果節(jié)點(diǎn)個數(shù)到達(dá)閾值,則將鏈表轉(zhuǎn)換為紅黑樹
- 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值均相同的節(jié)點(diǎn)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源碼片段 —— 擴(kuò)容resize():
- //可用來初始化HashMap大小 或重新調(diào)整HashMap大小 變?yōu)樵瓉?倍大小
- 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; // 擴(kuò)容閾值加倍
- }
- else if (oldThr > 0) // oldCap=0 ,oldThr>0此時newThr=0
- newCap = oldThr;
- else { // oldCap=0,oldThr=0 相當(dāng)于使用默認(rèn)填充比和初始容量 初始化
- 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];
- // 數(shù)組輔助到新的數(shù)組中,分紅黑樹和鏈表討論
- 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;
- }
看完以上源碼,是否感覺身體被掏空了?別慌,博主現(xiàn)在以一個簡單的小例子為主導(dǎo),帶領(lǐng)大家重新梳理一下。
簡析底層實(shí)現(xiàn)過程:
①創(chuàng)建HashMap,初始容量為16,實(shí)際容量 = 初始容量*負(fù)載因子(默認(rèn)0.75) = 12;
②調(diào)用put方法,會先計算key的hash值:hash = key.hashCode()。
③調(diào)用tableSizeFor()方法,保證哈希表散列均勻。
④計算Nodes[index]的索引:先進(jìn)行index = (tab.length - 1) & hash。
⑤如果索引位為null,直接創(chuàng)建新節(jié)點(diǎn),如果不為null,再判斷所因?yàn)樯鲜欠裼性?/p>
⑥如果有:則先調(diào)用hash()方法判斷,再調(diào)用equals()方法進(jìn)行判斷,如果都相同則直接用新的Value覆蓋舊的;
⑦如果不同,再判斷第一個節(jié)點(diǎn)類型是否為樹節(jié)點(diǎn)(涉及到:鏈表轉(zhuǎn)換成樹的閾值,默認(rèn)8),如果是,則按照紅黑樹的算法進(jìn)行存儲;如果不是,則按照鏈表存儲;
⑧當(dāng)存儲元素過多時,需要進(jìn)行擴(kuò)容:
默認(rèn)的負(fù)載因子是0.75,如果實(shí)際元素所占容量占分配容量的75%時就要擴(kuò)容了。大約變?yōu)?strong>原來的2倍(newThr =oldThr << 1);