本文首发于微信公众号【WriteOnRead】,欢送关注。
1. 概述
前文「JDK源码剖析-HashMap(1)」剖析了 HashMap 次要办法的实现原理(其余问题当前剖析),本文剖析下 LinkedHashMap。
先看一下 LinkedHashMap 的类继承结构图:
能够看到 LinkedHashMap 继承了 HashMap。
咱们晓得 HashMap 是无序的,即迭代器的程序与插入程序没什么关系。而 LinkedHashMap 在 HashMap 的根底上减少了程序:别离为「插入程序」和「拜访程序」。即遍历 LinkedHashMap 时,能够放弃与插入程序统一的程序;或者与拜访程序统一的程序。
LinkedHashMap 外部如何实现这两种程序的呢?它是通过一个双链表来维持的。因而能够将 LinkedHashMap 了解为「双链表 + 散列表」,或者“有序的散列表”。
2. 代码剖析
2.1 节点类 Entry
LinkedHashMap 外部有一个嵌套类 Entry,它继承自 HashMap 中的 Node 类,如下:
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); }}
static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; Node<K,V> next; Node(int hash, K key, V value, Node<K,V> next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } // ...}
该 Entry 类就是 LinkedHashMap 中的节点类。能够看到,它在 Node 类的根底上又减少了 before 和 after 两个变量,它们保留的是节点的前驱和后继(从字面意思也能够进行揣测),从而来保护 LinkedHashMap 的程序。
2.2 成员变量
/** * 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: true * for access-order, false for insertion-order. * LinkedHashMap 的迭代程序:true 为拜访程序;false 为插入程序。 */final boolean accessOrder;
2.3 结构器
- 结构器1
/** * Constructs an empty insertion-ordered LinkedHashMap instance * with the default initial capacity (16) and load factor (0.75). */public LinkedHashMap() { super(); accessOrder = false;}
这里的 super() 办法调用了 HashMap 的无参结构器。该结构器办法结构了一个容量为 16(默认初始容量)、负载因子为 0.75(默认负载因子)的空 LinkedHashMap,其程序为插入程序。
- 结构器 2、3、4、5
public LinkedHashMap(int initialCapacity) { super(initialCapacity); accessOrder = false;}public LinkedHashMap(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); accessOrder = false;}public LinkedHashMap(Map<? extends K, ? extends V> m) { super(); accessOrder = false; putMapEntries(m, false);}public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) { super(initialCapacity, loadFactor); this.accessOrder = accessOrder;}
能够看到下面几个结构器都是通过调用父类(HashMap)的结构器办法初始化,对此不再进行剖析。后面 4 个结构器的 accessOrder 变量默认值都为 false;最初一个略微不一样,它的 accessOrder 能够在初始化时指定,即指定 LinkedHashMap 的程序(插入或拜访程序)。
2.4 put 办法
LinkedHashMap 自身没有实现 put 办法,它通过调用父类(HashMap)的办法来进行读写操作。这里再贴下 HashMap 的 put 办法:
public V put(K key, V value) { return putVal(hash(key), key, value, false, true);}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) // 新的 bin 节点 tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; // key 已存在 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;}
这个办法哪个中央跟 LinkedHashMap 有分割呢?如何能放弃 LinkedHashMap 的程序呢?且看其中的 newNode() 办法,它在 HashMap 中的代码如下:
Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) { return new Node<>(hash, key, value, next);}
然而,LinkedHashMap 重写了该办法:
// 新建一个 LinkedHashMap.Entry 节点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;}
// link at the end of listprivate void linkNodeLast(LinkedHashMap.Entry<K,V> p) { LinkedHashMap.Entry<K,V> last = tail; tail = p; // list 为空 if (last == null) head = p; else { // 将新节点插入到 list 开端 p.before = last; last.after = p; }}
能够看到,每次插入新节点时,都会存到列表的开端。原来如此,LinkedHashMap 的插入程序就是在这里实现的。
此外,上文剖析 HashMap 时提到两个回调办法:afterNodeAccess 和 afterNodeInsertion。它们在 HashMap 中是空的:
// Callbacks to allow LinkedHashMap post-actionsvoid afterNodeAccess(Node<K,V> p) { }void afterNodeInsertion(boolean evict) { }
同样,LinkedHashMap 对它们进行了重写。先来剖析 afterNodeAccess 办法:
void afterNodeAccess(Node<K,V> e) { // move node to last LinkedHashMap.Entry<K,V> last; // accessOrder 为 true 示意拜访程序 if (accessOrder && (last = tail) != e) { // p 为拜访的节点,b 为其前驱,a 为其后继 LinkedHashMap.Entry<K,V> p = (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after; p.after = null; // p 是头节点 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; }}
为了便于剖析和了解,这里画出了两个操作示意图:
这里形容了进行该操作前后的两种状况。能够看到,该办法执行后,节点 p 被移到了 list 的开端。
2.5 get 办法
LinkedHashMap 重写了 HashMap 的 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;}
这里的 getNode 办法是父类的(HashMap)。若 accessOrder 为 true(即指定为拜访程序),则将拜访的节点移到列表开端。
LinkedHashMap 中重写的 afterNodeInsertion 办法:
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); }}// LinkedHashMap 中默认的返回值为 false,即这里的 removeNode 办法不执行protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { return false;}
removeNode 办法是父类 HashMap 中的:
final Node<K,V> removeNode(int hash, Object key, Object value, boolean matchValue, boolean movable) { Node<K,V>[] tab; Node<K,V> p; int n, index; // table 不为空,且给的的 hash 值所在位置不为空 if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) { Node<K,V> node = null, e; K k; V v; // 给定 key 对应的节点,在数组中第一个地位 if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) node = p; // 给定的 key 所在位置为红黑树或链表 else if ((e = p.next) != null) { if (p instanceof TreeNode) node = ((TreeNode<K,V>)p).getTreeNode(hash, key); else { do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { node = e; break; } p = e; } while ((e = e.next) != null); } } // 删除节点 if (node != null && (!matchValue || (v = node.value) == value || (value != null && value.equals(v)))) { if (node instanceof TreeNode) ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable); else if (node == p) tab[index] = node.next; else p.next = node.next; ++modCount; --size; // 删除节点后的操作 afterNodeRemoval(node); return node; } } return null;}
afterNodeRemoval 办法在 HashMap 中的实现也是空的:
void afterNodeRemoval(Node<K,V> p) { }
LinkedHashMap 重写了该办法:
void afterNodeRemoval(Node<K,V> e) { // unlink LinkedHashMap.Entry<K,V> p = (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after; p.before = p.after = null; if (b == null) head = a; else b.after = a; if (a == null) tail = b; else a.before = b;}
该办法就是双链表删除一个节点的操作。
3. 用法示例
3.1 LinkedHashMap 用法
咱们晓得 HashMap 是无序的,例如:
Map<String, String> map = new HashMap<>();map.put("bush", "a");map.put("obama", "b");map.put("trump", "c");map.put("lincoln", "d");System.out.println(map);// 输入后果(无序):// {obama=b, trump=c, lincoln=d, bush=a}
而若换成 LinkedHashMap,则能够放弃插入的程序:
Map<String, String> map = new LinkedHashMap<>();map.put("bush", "a");map.put("obama", "b");map.put("trump", "c");map.put("lincoln", "d");System.out.println(map);// 输入后果(插入程序):// {bush=a, obama=b, trump=c, lincoln=d}
指定 LinkedHashMap 的程序为拜访程序:
Map<String, String> map = new LinkedHashMap<>(2, 0.75f, true);map.put("bush", "a");map.put("obama", "b");map.put("trump", "c");map.put("lincoln", "d");System.out.println(map);map.get("obama");System.out.println(map);// 输入后果(插入程序):// {bush=a, obama=b, trump=c, lincoln=d}// 拜访 obama 后,obama 移到了开端// {bush=a, trump=c, lincoln=d, obama=b}
3.2 实现 LRU 缓存
private static class LRUCache<K, V> extends LinkedHashMap<K, V> { private int capacity; public LRUCache(int capacity) { super(16, 0.75f, true); this.capacity = capacity; } @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > capacity; }}
应用举例:
LRUCache<String, String> lruCache = new LRUCache<>(2);lruCache.put("bush", "a");lruCache.put("obama", "b");lruCache.put("trump", "c");System.out.println(lruCache);// 输入后果:// {obama=b, trump=c}
这里定义的 LRUCache 类中,对 removeEldestEntry 办法进行了重写,当缓存中的容量大于 2,时会把最早插入的元素 "bush" 删除。因而只剩下两个值。
4. 小结
- LinkedHashMap 继承自 HashMap,其构造能够了解为「双链表 + 散列表」;
- 能够保护两种程序:插入程序或拜访程序;
- 能够不便的实现 LRU 缓存;
- 线程不平安。