LinkedHashMap 源碼分析,底層竟這麼簡單!

  • 2020 年 2 月 21 日
  • 筆記

來源:cnblogs.com/panzi/p/10845079.html

LinkedHashMap 是一個鍵有序的 HashMap,可以將 LinkedHashMap 理解為 LinkList + HashMap。

所以研究 LinkedHashMap 之前要先看 HashMap 程式碼,這裡不再贅述。

其實 LinkedHashMap 無非就是通過鏈表結構將存儲在 HashMap 中的數據通過 beofre,after連接起來。

作為一個鏈表結構 head,tail 必不可少

/**   * The head (eldest) of the doubly linked list.   */  transient LinkedHashMap.Entry<K,V> head;    /**   * The tail (youngest) of the doubly linked list.   */  transient LinkedHashMap.Entry<K,V> tail;

還要有一個存儲 前節點和後節點的數據結構


最後,為了支援節點根據訪問頻率更新節點順序,增加了 accessOrder 變數

/**   * The iteration ordering method for this linked hash map: <tt>true</tt>   * for access-order, <tt>false</tt> for insertion-order.   *   * @serial   */  final boolean accessOrder;

LinkedHashMap中的 put 方法沒有重寫,其實就是 HashMap 中的 put 方法。不過它給子類留了可供重寫的方法。

afterNodeAccess(e) 和 afterNodeInsertion(evict);

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)      n = (tab = resize()).length;    if ((p = tab[i = (n - 1) & hash]) == null)      tab[i] = newNode(hash, key, value, null);    else {      Node<K,V> e; K k;      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) {          if ((e = p.next) == null) {            p.next = newNode(hash, key, value, null);            if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st              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;        if (!onlyIfAbsent || oldValue == null)          e.value = value;        //        afterNodeAccess(e);        return oldValue;      }    }    ++modCount;    if (++size > threshold)      resize();    //    afterNodeInsertion(evict);    return null;  }

afterNodeInsertion 當有新節點插入時,是否刪除第一個節點,removeEldestEntry在此類中返回了 false,所以,不會刪除任何一個節點。

    // possibly remove eldest  void afterNodeInsertion(boolean evict) {    LinkedHashMap.Entry<K,V> first;      if (evict && (first = head) != null && removeEldestEntry(first)) {      K key = first.key;      removeNode(hash(key), key, null, false, true);    }  }

另外,LinkedHashMap 重寫了 newNode方法。以將新節點插入到鏈表最後一個節點上

tab[i] = newNode(hash, key, value, null);    Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {    LinkedHashMap.Entry<K,V> p =      new LinkedHashMap.Entry<K,V>(hash, key, value, e);    linkNodeLast(p);    return p;  }  private void linkNodeLast(LinkedHashMap.Entry<K,V> p) {    LinkedHashMap.Entry<K,V> last = tail;    tail = p;    if (last == null)      head = p;    else {      p.before = last;      last.after = p;    }  }

afterNodeAccess 當節點更新時,或者調用 get,getOrDefault 方法時,會根據 accessOrder 為true或者false執行該方法。

void afterNodeAccess(Node<K,V> e) {    LinkedHashMap.Entry<K,V> last;    //需要改變順序 並且 當前節點不是最後一個    if (accessOrder && (last = tail) != e) {      // b 當前節點之前的節點      // a 當前節點之後的節點      LinkedHashMap.Entry<K,V> p =        (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;      //需要將p節點置為最後一個節點,所以置 p節點的 after 為 null      p.after = null;        B->P->A ===> B->P->E      //如果沒有前一個節點,所以 後一個節點置為 頭節點      if (b == null)        head = a;      else        //否則 將 b.after 置為 a        b.after = a;        // B->P->A ===> B->A      if (a != null)        a.before = b;      else        // B->P->NULL ===> B->A        last = b;      //如果 last 為 null,將 p 置為頭結點      if (last == null)        head = p;      else {        //B -> P -> NULL        p.before = last;        last.after = p;      }      //最後將tail置為 p 節點      tail = p;      ++modCount;    }  }

簡單看了一下程式碼結構,雖然細節很多都沒看,但是大體上的實現就是多了一層封裝,通過鏈表結構實現順序存儲並且還能達到 O(1)的插入和刪除,查找操作。

END