[源碼分析]LinkedHashMap

一個鍵有序的 HashMap

  能夠將 LinkedHashMap 理解爲 LinkList + HashMap,因此研究LinkedHashMap以前要先看HashMap代碼。這裏再也不贅述。其實LinkedHashMap無非就是經過鏈表結構將存儲在HashMap中的數據經過 beofre,after鏈接起來。node

方法

做爲一個鏈表結構 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;

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

/**
     * HashMap.Node subclass for normal LinkedHashMap entries.
     */
    static class Entry<K,V> extends HashMap.Node<K,V> {
        Entry<K,V> before, after;
        Entry(int hash, K key, V value, Node<K,V> next) {
            super(hash, key, value, next);
        }
    }

最後,爲了支持節點根據訪問頻率更新節點順序,增長了 accessOrder 變量this

/**
     * 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;

put 方法

LinkedHashMap中的put方法沒有重寫,其實就是HashMap中的put方法。不過它給子類留了可供重寫的方法。 afterNodeAccess(e) 和 afterNodeInsertion(evict);3d

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方法。以將新節點插入到鏈表最後一個節點上code

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)的插入和刪除,查找操做。orm

相關文章
相關標籤/搜索