#LinkedHashMapjava
繼承
HashMap,put
調用HashMap
的put
,區別在於HashMap單向鏈表
,LinkedHashMap雙向鏈表
//hashMap static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; Node<K,V> next; ...... } //LinkedHashMap 包裝hashMap的Node,多了順序引用 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); } }
hashMap.add - > LinkedHashMap.newNode
,構造LinkHashMap.Node
雙向鏈表節點包裝HashMap.Node
//持有頭節點 transient LinkedHashMap.Entry<K,V> head; //尾節點 transient LinkedHashMap.Entry<K,V> tail; 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) //調用子類LinkedHashMap 的newNode tab[i] = newNode(hash, key, value, null); else { 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; } }
//正常插入,遍歷有序 public V get(Object key) { Node<K,V> e; //HashMap.getNode 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; } }