所使用的jdk版本为1.8.0_172版本,先看一下 LinkedHashMap<K,V> 在JDK中Map的UML类图中的主要继承实现关系:
概述
从上图中我们可以看到LinkedHashMap是HashMap的子类,在继承HashMap的功能之上,LinkedHashMap主要实现了具有可预知迭代顺序的功能。我们知道HashMap中迭代遍历顺序与我们 put 映射的顺序是无关的,而HashMap提供了两种映射迭代遍历顺序的实现,一是映射的放入顺序,另一种是映射的访问顺序(从近期访问最少到近期访问最多的顺序,适合 LRU 算法缓存类设计)。
LinkedHashMap<K,V> 的继承实现结构:
public class LinkedHashMap<K,V>
extends HashMap<K,V>
implements Map<K,V>
{
LinkedHashMap 默认采用映射插入顺序:
public class Test {
public static void main(String[] args) {
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(3, "three");
hashMap.put(2, "two");
hashMap.put(1, "one");
System.out.println(hashMap);
LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put(3, "three");
linkedHashMap.put(2, "two");
linkedHashMap.put(1, "one");
System.out.println(linkedHashMap);
}
}
程序输出结果:
{1=one, 2=two, 3=three}
{3=three, 2=two, 1=one}
LinkedHashMap 启用映射的访问顺序(从近期访问最少到近期访问最多的顺序):
public class Test {
public static void main(String[] args) {
LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<>(14,.75f,true);
linkedHashMap.put(3, "three");
linkedHashMap.put(2, "two");
linkedHashMap.put(1, "one");
System.out.println(linkedHashMap);
linkedHashMap.get(3);
System.out.println(linkedHashMap);
linkedHashMap.put(2, "two");
System.out.println(linkedHashMap);
}
}
程序输出结果:
{3=three, 2=two, 1=one}
{2=two, 1=one, 3=three}
{1=one, 3=three, 2=two}
顺序:最近被访问的映射放在最后面。需要注意哪些方法被视为映射被访问了:put、putIfAbsent、get、getOrDefault、compute、computeIfAbsent、computeifprent、merge、replace 这些方法会导致对相应映射项的访问(假设该映射存在)。putAll 方法以指定映射的条目集迭代器提供的键-值映射关系的顺序,为指定映射的每个映射关系生成一个条目访问,即 putAll 方法放入的映射是在LIinkedHashMap 的最后面的。特别地,collection 视图上的操作不影响底层映射的迭代顺序。
数据结构
LinkedHashMap 是 HashMap 和 链表 二者的实现,它在HashMap的结构之上,引入双向链表来维护Map节点的迭代顺序,可以理解为就是利用双向链表把HashMap节点按照顺序串联起来。
LinkedHashMap 中的节点 Entry<K,V> 类,继承了 HashMap 中的 Node 类,但同时 HashMap 中的红黑树节点类型 TreeNode 继承了 LinkedHashMap 中的 Entry<K,V> 类:
/**
* LinkedHashMap中的Entry<K,V>节点是HashMap中Node<K,V>节点的子类
*/
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);
}
}
既然是双端链表的实现,自然有对应的头节点和尾节点:
/**
* The head (eldest) of the doubly linked list.
*/
/**
* 双链表的头(距上次被访问时间间隔最长的节点)
*/
transient LinkedHashMap.Entry<K,V> head;
/**
* The tail (youngest) of the doubly linked list.
*/
/**
* 双链表的尾(最近被访问的节点,即距上次被访问时间间隔最长的节点)
*/
transient LinkedHashMap.Entry<K,V> tail;
还有一个重要的属性字段用于构造方法是否启用访问顺序:
/**
* The iteration ordering method for this linked hash map: <tt>true</tt>
* for access-order, <tt>false</tt> for insertion-order.
*
* @serial
*/
/**
* 此链接的哈希映射的迭代排序方法:
* true:按照访问顺序
* false:按照插入顺序
*
* @serial
*/
final boolean accessOrder;
实现原理
put(K key, V value) 方法
LinkedHashMap 并没有重写 put 方法,而是直接继承的 HashMap 中的 put 方法。LinkedHashMap 重写了一些钩子方法,比如 newNode 方法等,以及还记得在上一篇讲述HashMap文章中,在 put 方法中我们提到有几个钩子(或者叫回调)方法在HashMap中都是空实现,LinkedHashMap 就是通过重写这些方法来实现维护 put 节点的插入顺序或者访问顺序的(本质上就是维护调整双向链表中的节点顺序):
HashMap 中的空回调方法:
// Callbacks to allow LinkedHashMap post-actions
void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node<K,V> p) { }
HashMap 中的newNode 等钩子方法:
// Create a regular (non-tree) node
Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
return new Node<>(hash, key, value, next);
}
// Create a tree bin node
TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) {
return new TreeNode<>(hash, key, value, next);
}
// For treeifyBin
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
return new TreeNode<>(p.hash, p.key, p.value, next);
}
//还有一些其它的......
再简单过一下 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;
//通过resize()方法初始化table
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//(n - 1) & hash 相当于 hash % n;如果数组中该位置为null,即没有被使用,直接构造新的Node节点放入
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {//如果数组中的该位置已经被占用
Node<K,V> e; K k;
//如果链表的第一个节点或者树的根节点的key与待放入的key相同,
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;//用一个临时节点e记录
//如果数组table中的位置不是该键,并且数组中的节点是红黑树节点,则按红黑树节点处理
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//如果数组table中的位置不是该键,并且数组中的节点是链表结构节点
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//判断链表的长度是否大于 8
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
/*如果数组的长度没有超过64,则进行扩容操作;
*如果数组长度超过64,则把冲突的链表结构转换为红黑树结构*/
treeifyBin(tab, hash);
break;
}
//如果链表中已经存在了待插入的key,跳出循环
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//key已经存在的情况,用新值替换旧值,返回旧值
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
//回调方法,提供给 LinkedHashMap 后处理的回调,这里为空实现
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//如果HashMap中映射的数量达到了阈值,则触发扩容操作
//如果数据量很大,扩容的时间开销不可忽略,要考虑到。
if (++size > threshold)
resize();
afterNodeInsertion(evict);//提供给LinkedHashMap使用的回调,这里为空实现
return null;
}
1、如果是新的 key 插入的情况,LinkedHashMap 重写了newNode 方法以及 newTreeNode 方法等钩子方法,在创建新的节点的时候就会按照插入顺序维护双向链表,具体由 linkNodeLast 方法实现:
LinkedHashMap中重写的一些钩子方法:
// overrides of HashMap hook methods
void reinitialize() {
super.reinitialize();
head = tail = null;
}
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;
}
Node<K,V> replacementNode(Node<K,V> p, Node<K,V> next) {
LinkedHashMap.Entry<K,V> q = (LinkedHashMap.Entry<K,V>)p;
LinkedHashMap.Entry<K,V> t =
new LinkedHashMap.Entry<K,V>(q.hash, q.key, q.value, next);
transferLinks(q, t);
return t;
}
TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) {
TreeNode<K,V> p = new TreeNode<K,V>(hash, key, value, next);
linkNodeLast(p);
return p;
}
linkNodeLast 方法实现:
// link at the end of list
// 将节点放到链表末尾
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;
}
}
另外,新插入节点后会执行 afterNodeInsertion 方法,该方法在 LinkedHashMap 中的实现为:
void afterNodeInsertion(boolean evict) { // possibly remove eldest
// evict 在 HashMap 的 put 方法中传入的是 true
// removeEldestEntry 可以看作是LinkedHashMap 透出的钩子方法,本类中直接返回 false
LinkedHashMap.Entry<K,V> first;
if (evict && (first = head) != null && removeEldestEntry(first)) {
K key = first.key;
removeNode(hash(key), key, null, false, true);
}
}
removeEldestEntry 方法用于那些当作缓存的子类,这些缓存子类往往有大小限制,新加入一个映射元素,便删除掉最老的(距离上次被访问到间隔时间最长的)那个映射节点。
2、当一个 key 已经存在的情况,此时会去执行 afterNodeAccess 方法,该方法在 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;
}
}
正如注释一样,该方法功能就是如果开启了访问顺序功能(accessOrder 字段为 true),就会把认为被访问的节点放在双向链表的最尾端。
get(Object key) 方法
LinkedHashMap 重写了 get 方法,主要是为了访问顺序功能的实现:
public V get(Object key) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) == null)
return null;
if (accessOrder)
afterNodeAccess(e);
return e.value;
}
LinkedHashIterator 迭代器
HashMap 中的迭代器是 HashIterator,它迭代遍历顺序是按照 Node数组的顺序遍历, 如果数组上的节点是链表或者树节点,则先遍历该条链表或者树结构,再遍历下一个数组位置元素。
LinkedHashMap 中的迭代器是 LinkedHashIterator,从双向链表中的头节点开始遍历双向链表即可:
abstract class LinkedHashIterator {
LinkedHashMap.Entry<K,V> next;
LinkedHashMap.Entry<K,V> current;
int expectedModCount;
LinkedHashIterator() {
//双向链表中的头节点开始遍历
next = head;
expectedModCount = modCount;
current = null;
}
public final boolean hasNext() {
return next != null;
}
final LinkedHashMap.Entry<K,V> nextNode() {
LinkedHashMap.Entry<K,V> e = next;
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (e == null)
throw new NoSuchElementException();
current = e;
next = e.after;
return e;
}
public final void remove() {
Node<K,V> p = current;
if (p == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
current = null;
K key = p.key;
removeNode(hash(key), key, null, false, false);
expectedModCount = modCount;
}
}
关于 HashMap 和 LinkedHashMap 的迭代遍历顺序代码:
public static void main(String[] args) {
HashMap<Integer, String> hashMap = new HashMap<>(14,.75f);
hashMap.put(1, "one");
hashMap.put(15, "fifteen");
hashMap.put(17, "seventeen");//注意 17 和 1 有 hash 碰撞
hashMap.put(3, "three");
hashMap.put(2, "two");
System.out.println(hashMap);
LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<>(14,.75f);
linkedHashMap.put(1, "one");
linkedHashMap.put(15, "fifteen");
linkedHashMap.put(17, "seventeen");
linkedHashMap.put(3, "three");
linkedHashMap.put(2, "two");
System.out.println(linkedHashMap);
}
程序输出结果:
{1=one, 17=seventeen, 2=two, 3=three, 15=fifteen}
{1=one, 15=fifteen, 17=seventeen, 3=three, 2=two}