对于HashMap我们可能比较熟悉,HashMap中的键值对节点并不是有序的,如果在我们日常开发中有需要保存键值对的顺序时就可以使用LinkedHashMap,从字面上可以看出这是一个基于链表的有序HashMAP。
LinkedHashMap常用的API大部分和HashMap是差不多的,但是在内部实现机制上和HashMap有些地方还是有所不同的。
首先我们来看LinkedHashMap的继承关系
从继承关系可以看出继承HashMap,并实现了Map的接口,所以暴露的接口基本上和HashMap一样。但是可HashMap的最大区别就是LinkedHashMap有序的,接下里我们将探讨有序是如何实现的。
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中Entry节点,但是HashMap中最大的不同就是在每个节点中添加了按照顺序添加的上一个节点before和下一个节点after的引用,就像链表一样把节点安照顺序串联起来了。
transient LinkedHashMap.Entry<K,V> head;
/**
* The tail (youngest) of the doubly linked list.
*/
transient LinkedHashMap.Entry<K,V> tail;
同时保留了链表的头结点head和尾节点after。
接下来看看LinkedHashMap的put方法的实现,但是LinkedHashMap并没有重写put方法,那么LinkedHashMap是怎么按照添加顺序把节点都串联起来了呢,既然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;
}
前面的添加操作并不需要过多解释,在后面的代码我们注意到调用了afterNodeAccess这个方法,在HashMap我们找到了这个方法
// Callbacks to allow LinkedHashMap post-actions
void afterNodeAccess(Node<K,V> p) { }
这个方法方法体是空的,目的就是让LinkedHashMap重写这个人方法,以至于在调用put方法时把节点串联起来,我们来看看LinkedHashMap中这个方法的重写版本
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;
}
}
从代码中可以看出来这个一个在双向链表添加的操作,这就解释了LinkedHashMap如何保证了键值对的顺序了。