JDK1.8 LinkedHashMap和LinkedHashSet有序分析

基于JDK1.8的源码分析

LinkedHashMap 有序原理分析

LinkedHashMap中的Entry重写了.

static class Entry<K,V> extends HashMap.Node<K,V> {

//每个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 =
new LinkedHashMap.Entry<K,V>(hash, key, value, e);
//把新建的节点放入Entry链表尾部
linkNodeLast(p);
return p;
}

linkNodeLast方法

//这里会把Entry按照insert顺序插入到链表尾部,所以实现了访问的有序性
// link at the end of list
private void linkNodeLast(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;
}
}

按照节点访问顺序来排序


void afterNodeAccess(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;
}
}

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

LinkedHashSet 有序原理分析

首先LinkedHashSet继承自HashSet

查看LinkedHash构造器源码

LinkedHashSet构造器

/**
* Constructs a new, empty linked hash set with the default initial
* capacity (16) and load factor (0.75).
*/
public LinkedHashSet() {
// 调用父类Haset构造器
super(16, .75f, true);
}

HashSet构造器

HashSet(int initialCapacity, float loadFactor, boolean dummy) {
// map的实现使用了LinkedHashMap
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}

因为LinkedHashSet中使用的map实现是LinkedHashMap,所以天然有序

具体见上文分析