分析一下 LinkedHashMap 源碼,看下內部結構,研究一下如何保證訪問順序。java
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>
LinkedHashMap 繼承自 HashMap,是HashMap的一個子類。node
/** * 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); } } private static final long serialVersionUID = 3801124242820219131L; /** * 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; /** * 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;
Entry 類繼承自 HashMap.Node,增長了2個變量,before, after。來維護每一個Node前面一個對象和後面一個對象。head, tail 變量維護鏈表頭和尾。accessOrder 爲true表示按訪問順序來遍歷(訪問過的元素放到鏈表的尾部),爲false表示按插入順序遍歷。數組
其實主要的內部結構仍是和 HashMap 同樣的,只不過在HashMap的基礎上每一個Node都加上了先後2個對象的引用。它的大體結構是這樣。網絡
圖片來自網絡app
遍歷一個LinkedHashMap,默認按照插入順序來顯示。結合 這篇文章 HashIterator 的介紹,看下 LinkedHashMap 是怎麼遍歷的。this
public Set<Map.Entry<K,V>> entrySet() { Set<Map.Entry<K,V>> es; return (es = entrySet) == null ? (entrySet = new LinkedEntrySet()) : es; } final class LinkedEntryIterator extends LinkedHashIterator implements Iterator<Map.Entry<K,V>> { public final Map.Entry<K,V> next() { return nextNode(); } } abstract class LinkedHashIterator { LinkedHashMap.Entry<K,V> next; LinkedHashMap.Entry<K,V> current; int expectedModCount; LinkedHashIterator() { next = head; expectedModCount = modCount; current = null; } final LinkedHashMap.Entry<K,V> nextNode() { LinkedHashMap.Entry<K,V> e = next; if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (e == null) throw new NoSuchElementException(); current = e; next = e.after; return e; } ... }
原理和HashMap差很少,可是 LinkedHashMap 的遍歷(看nextNode方法)是從 head 開始遍歷,直到 Entry 的 after 字段爲空。spa
get 方法.net
public V get(Object key) { Node<K,V> e; if ((e = getNode(hash(key), key)) == null) return null; if (accessOrder) afterNodeAccess(e); return e.value; } void afterNodeAccess(Node<K,V> e) { // move node to last LinkedHashMap.Entry<K,V> last; if (accessOrder && (last = tail) != e) { LinkedHashMap.Entry<K,V> p = (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after; p.after = null; if (b == null) head = a; else b.after = a; if (a != null) a.before = b; else last = b; if (last == null) head = p; else { p.before = last; last.after = p; } tail = p; ++modCount; } }
get 方法和 HashMap 的基本同樣,可是多了一個 afterNodeAccess 方法,當 accessOrder 爲 true 的時候執行這個方法,將訪問過的node放到鏈表的最後。code
LinkedHashMap linkedHashMap = new LinkedHashMap(16, 0.75f , true);
也就是像這樣初始化一個 LinkedHashMap 以後,每次訪問過一個對象以後這個對象就被放到了鏈表的最後。orm
put 方法
其實 LinkedHashMap 本身沒有實現 put 方法,仍是調用的是 HashMap 的 put 方法
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; }
這裏有一個 newNode(hash, key, value, null),LinkedHashMap 重寫了這個方法
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; } // link at the end of list 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; } }
因爲Java多態的特性,put方法實際生成的是 LinkedHashMap.Entry 類,而且將這個node放到了整個鏈表的最後(linkNodeLast)。
remove 方法
LinkedHashMap 也是調用的 HashMap 的 remove 方法
final Node<K,V> removeNode(int hash, Object key, Object value, boolean matchValue, boolean movable) { Node<K,V>[] tab; Node<K,V> p; int n, index; if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) { Node<K,V> node = null, e; K k; V v; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) node = p; else if ((e = p.next) != null) { if (p instanceof TreeNode) node = ((TreeNode<K,V>)p).getTreeNode(hash, key); else { do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { node = e; break; } p = e; } while ((e = e.next) != null); } } if (node != null && (!matchValue || (v = node.value) == value || (value != null && value.equals(v)))) { if (node instanceof TreeNode) ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable); else if (node == p) tab[index] = node.next; else p.next = node.next; ++modCount; --size; afterNodeRemoval(node); return node; } } return null; }
出方法前有一個 afterNodeRemoval(node) 方法,LinkedHashMap 重寫了這個方法
void afterNodeRemoval(Node<K,V> e) { // unlink LinkedHashMap.Entry<K,V> p = (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after; p.before = p.after = null; if (b == null) head = a; else b.after = a; if (a == null) tail = b; else a.before = b; }
由於內部有一個鏈表,因此刪除的時候也要維護一下鏈表關係。
LinkedHashMap 做爲 HashMap 的子類,重寫了其中一些方法,擴展了 Node 類,使其具備了按順序遍歷數據的功能。在內部維護了一個鏈表,在put/remove方法中,在數組中操做元素的同時,維護了一個鏈表。