所使用的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}