LinkedHashMap是HashMap的子类,与HashMap有着同样的存储结构,但它加入了一个双向链表的头结点,将所有put到LinkedHashmap的节点一一串成了一个双向循环链表,因此它保留了节点插入的顺序,可以使节点的输出顺序与输入顺序相同。
LinkedHashMap可以用来实现LRU算法,LinkedHashMap同样是非线程安全的,只在单线程环境下使用。
public class LinkedHashMap<K,V>
extends HashMap<K,V>
implements Map<K,V>
{
/**
* 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);
}
}
transient LinkedHashMap.Entry<K,V> head;
transient LinkedHashMap.Entry<K,V> tail;
final boolean accessOrder;
LinkedHashMap 的Entry 是继承自HashMap.Node,在该node中before、after的属性保存链的前后关系,head、tail是LinkedHashMap的双向循环链表的头、尾结点,accessOrder是双向链表中元素排序规则的标志位,true表示按访问顺序排序,false表示按插入顺序排序。默认是false,即按插入顺序排序,可以在构造时指定。
LinkedHashMap在节点的创建node时重写了HashMap类中newNode函数:
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;
}
可以看到,除了新建一个结点之外,还把这个结点链接到双链表的末尾了,这个操作维护了插入顺序。
在HashMap源码中有:
// Callbacks to allow LinkedHashMap post-actions
void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node<K,V> p) { }
上述这些方法都是LinkedHashMap重写的,在Map的put、set等方法调用时回调这些方法,这些方法则会调整双向链表中的节点顺序。
LinkedHashMap对containsValue、迭代时,充分利用了双向链表的结构,避免了对原始数组的访问。
那LinkedHashMap是如何实现LRU的?当accessOrder为true时,会开启按访问顺序排序的模式,才能用来实现LRU算法。无论是put方法还是get方法,都会导致目标Entry成为最近访问的Entry,因此便把该Entry加入到了双向链表的末尾,这样便把最近使用了的Entry放入到了双向链表的后面,多次操作后,双向链表前面的Entry便是最近没有使用的,这样当节点个数满的时候,删除的最前面的Entry便是最近最少使用的Entry。