1. 前言


          上一篇從源碼方面了解了JDK1.7中Hashmap的實(shí)現(xiàn)原理,可以看到其源碼相對(duì)還是比較簡(jiǎn)單的。本篇筆者和大家一起學(xué)習(xí)下JDK1.8下Hashmap的實(shí)現(xiàn)。JDK1.8中對(duì)Hashmap做了以下改動(dòng)。

          * 默認(rèn)初始化容量=0
          * 引入紅黑樹(shù),優(yōu)化數(shù)據(jù)結(jié)構(gòu)
          * 將鏈表頭插法改為尾插法,解決1.7中多線程循環(huán)鏈表的bug
          * 優(yōu)化hash算法
          * resize計(jì)算索引位置的算法改進(jìn)
          * 先插入后擴(kuò)容
          2. Hashmap中put()過(guò)程

          筆者的源碼是OpenJDK1.8的源碼。

          JDK1.8中,Hashmap將基本元素由Entry換成了Node,不過(guò)查看源碼后發(fā)現(xiàn)換湯不換藥,這里沒(méi)啥好說(shuō)的。

          下圖是一位大神級(jí)別畫(huà)的圖,自己就不再造輪子了??凸僬?qǐng)看



          put()源碼如下
          public V put(K key, V value) { return putVal(hash(key), key, value, false,
          true); } final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean
          evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; // 判斷數(shù)組是否為空,長(zhǎng)度是否為0,是則進(jìn)行擴(kuò)容數(shù)組初始化
          if ((tab = table) == null || (n = tab.length) == 0) n = (tab =
          resize()).length; // 通過(guò)hash算法找到數(shù)組下標(biāo)得到數(shù)組元素,為空則新建 if ((p = tab[i = (n - 1) &
          hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K
          k; // 找到數(shù)組元素,hash相等同時(shí)key相等,則直接覆蓋 if (p.hash == hash && ((k = p.key) == key ||
          (key != null && key.equals(k)))) e = p; // 該數(shù)組元素在鏈表長(zhǎng)度>8后形成紅黑樹(shù)結(jié)構(gòu)的對(duì)象,p為樹(shù)結(jié)構(gòu)已存在的對(duì)象
          else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab,
          hash, key, value); else { // 該數(shù)組元素hash相等,key不等,同時(shí)鏈表長(zhǎng)度<8.進(jìn)行遍歷尋找元素,有就覆蓋無(wú)則新建 for
          (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { // 新建鏈表中數(shù)據(jù)元素,尾插法
          p.next = newNode(hash, key, value, null); if (binCount >= TREEIFY_THRESHOLD -
          1) // -1 for 1st // 鏈表長(zhǎng)度>=8 結(jié)構(gòu)轉(zhuǎn)為 紅黑樹(shù) treeifyBin(tab, hash); break; } if (e.hash
          == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p =
          e; } } // 新值覆蓋舊值 if (e != null) { // existing mapping for key V oldValue =
          e.value; // onlyIfAbsent默認(rèn)false if (!onlyIfAbsent || oldValue == null) e.value
          = value; afterNodeAccess(e); return oldValue; } } ++modCount; // 判斷是否需要擴(kuò)容 if
          (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
          基本過(guò)程如下:

          *
          檢查數(shù)組是否為空,執(zhí)行resize()擴(kuò)充;在實(shí)例化HashMap時(shí),并不會(huì)進(jìn)行初始化數(shù)組)

          *
          通過(guò)hash值計(jì)算數(shù)組索引,獲取該索引位的首節(jié)點(diǎn)。

          *
          如果首節(jié)點(diǎn)為null(沒(méi)發(fā)生碰撞),則創(chuàng)建新的數(shù)組元素,直接添加節(jié)點(diǎn)到該索引位(bucket)。

          *
          如果首節(jié)點(diǎn)不為null(發(fā)生碰撞),那么有3種情況

          ① key和首節(jié)點(diǎn)的key相同,覆蓋old value(保證key的唯一性);否則執(zhí)行②或③

          ② 如果首節(jié)點(diǎn)是紅黑樹(shù)節(jié)點(diǎn)(TreeNode),將鍵值對(duì)添加到紅黑樹(shù)。

          ③ 如果首節(jié)點(diǎn)是鏈表,進(jìn)行遍歷尋找元素,有就覆蓋無(wú)則新建,將鍵值對(duì)添加到鏈表。添加之后會(huì)判斷鏈表長(zhǎng)度是否到達(dá)TREEIFY_THRESHOLD -
          1這個(gè)閾值,“嘗試”將鏈表轉(zhuǎn)換成紅黑樹(shù)。

          *
          最后判斷當(dāng)前元素個(gè)數(shù)是否大于threshold,擴(kuò)充數(shù)組。

          3. Hashmap中g(shù)et()過(guò)程
          public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key))
          == null ? null : e.value; } 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) { // 永遠(yuǎn)檢查第一個(gè)node
          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) // 樹(shù)查找 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; }
          在Hashmap1.8中,無(wú)論是存元素還是取元素,都是優(yōu)先判斷bucket上第一個(gè)元素是否匹配,而在1.7中則是直接遍歷查找。

          基本過(guò)程如下:

          * 根據(jù)key計(jì)算hash;
          * 檢查數(shù)組是否為空,為空返回null;
          * 根據(jù)hash計(jì)算bucket位置,如果bucket第一個(gè)元素是目標(biāo)元素,直接返回。否則執(zhí)行4;
          * 如果bucket上元素大于1并且是樹(shù)結(jié)構(gòu),則執(zhí)行樹(shù)查找。否則執(zhí)行5;
          * 如果是鏈表結(jié)構(gòu),則遍歷尋找目標(biāo)
          4. Hashmap中resize()過(guò)程
          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) { // 如果已達(dá)到最大容量不在擴(kuò)容 if (oldCap >= MAXIMUM_CAPACITY) { threshold
          = Integer.MAX_VALUE; return oldTab; } // 通過(guò)位運(yùn)算擴(kuò)容到原來(lái)的兩倍 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 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); } // 新的擴(kuò)容臨界值
          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; // 如果該位置元素沒(méi)有next節(jié)點(diǎn),將該元素放入新數(shù)組 if (e.next == null)
          newTab[e.hash & (newCap - 1)] = e; else if (e instanceof TreeNode) // 樹(shù)節(jié)點(diǎn)
          ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { // preserve order //
          鏈表節(jié)點(diǎn)。 // lo串的新索引位置與原先相同 Node<K,V> loHead = null, loTail = null; //
          hi串的新索引位置為[原先位置j+oldCap] Node<K,V> hiHead = null, hiTail = null; Node<K,V>
          next; do { next = e.next; // 原索引,oldCap是2的n次方,二進(jìn)制表示只有一個(gè)1,其余是0 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); //
          根據(jù)hash判斷該bucket上的整個(gè)鏈表的index還是舊數(shù)組的index,還是index+oldCap if (loTail != null) {
          loTail.next = null; newTab[j] = loHead; } if (hiTail != null) { hiTail.next =
          null; newTab[j + oldCap] = hiHead; } } } } } return newTab; }
          JDK1.8版本中擴(kuò)容相對(duì)復(fù)雜。在1.7版本中,重新根據(jù)hash計(jì)算索引位置即可;而在1.8版本中分2種情況,下邊用圖例來(lái)解釋。





          5. 總結(jié)

          其余還有為什么閾值=8轉(zhuǎn)紅黑樹(shù),長(zhǎng)度<=6 轉(zhuǎn)鏈表這些問(wèn)題?;径际菙?shù)據(jù)科學(xué)家根據(jù)概率做出的經(jīng)驗(yàn)值,同時(shí)避免數(shù)據(jù)結(jié)構(gòu)頻繁的轉(zhuǎn)換引起的性能開(kāi)銷(xiāo)。

          整體看來(lái),JDK1.8主要在數(shù)據(jù)結(jié)構(gòu)、算法和性能上對(duì)1.7進(jìn)行了優(yōu)化。

          6. AD

          歡迎大家關(guān)注公眾號(hào)【當(dāng)我遇上你】, 每天第一時(shí)間與您分享干貨。


          友情鏈接
          ioDraw流程圖
          API參考文檔
          OK工具箱
          云服務(wù)器優(yōu)惠
          阿里云優(yōu)惠券
          騰訊云優(yōu)惠券
          京東云優(yōu)惠券
          站點(diǎn)信息
          問(wèn)題反饋
          郵箱:[email protected]
          QQ群:637538335
          關(guān)注微信

                插逼喷水视频 | 国产a小视频 | 纲手好紧蕾丝内裤动态图小说 | 男ji大巴进入女人的网站 | 大乳少妇p00ps巨大吃奶 |