//每个Entry增加了before,after,双向链表 Entry<K,V> before, after; Entry(int hash, K key, V value, Node<K,V> next) { super(hash, key, value, next); } }
put方法
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }
putVal方法
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) //重点是newNode这个方法 tab[i] = newNode(hash, key, value, null); // 后续省略... }
newNode方法
LinkedHashMap重写了该方法
Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) { LinkedHashMap.Entry<K,V> p = newLinkedHashMap.Entry<K,V>(hash, key, value, e); //把新建的节点放入Entry链表尾部 linkNodeLast(p); return p; }
linkNodeLast方法
//这里会把Entry按照insert顺序插入到链表尾部,所以实现了访问的有序性 // link at the end of list privatevoidlinkNodeLast(LinkedHashMap.Entry<K,V> p) { LinkedHashMap.Entry<K,V> last = tail; tail = p; //如果第一次put元素 if (last == null) // head = tail; head = p; else { // 新插入的节点的前驱节点指向之前的tail p.before = last; //之前的tail的后继节点指向新节点 // oldTail->after = p; // p->before = oldTail // tail-> p last.after = p; } }
按照节点访问顺序来排序
voidafterNodeAccess(Node<K,V> e) { // move node to last
LinkedHashMap.Entry<K,V> last; // accessOrder 默认为false,按插入顺序来访问,否则把访问过的元素放在链表后面 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; } }