JAVA集合三Map—— 03LinkedHashMap
*特別聲明:
*本文分析基於JDK8
*轉載請註明源地址。
一、LinkedHashMap
LinkedHashMap 是一種有迭代順序的HashMap。繼承於HashMap,可以說是LinkedList和HashMap的結合體。
LinkedHashMap 定義的默認迭代順序是按照插入的順序來迭代,並且重複插入相同key,不會改變順序。也可以通過設置accessOrder的值來改變順序。設置爲true,則表示按照存取順序來迭代。其實存取的時候,如果設置爲true會將當前節點放置在鏈表末尾,後面會看到源碼。
accessOrder的定義:
/**
* The iteration ordering method for this linked hash map: <tt>true</tt>
* for access-order, <tt>false</tt> for insertion-order.
*
* @serial
*/
final boolean accessOrder;
該字段可以通過3個參數的構造函數來設置。使用其他構造函數,則默認值爲false。
public LinkedHashMap(int initialCapacity,
float loadFactor,
boolean accessOrder) {
super(initialCapacity, loadFactor);
this.accessOrder = accessOrder;
}
二、數據結構
LinkedHashMap的存儲結構和HashMap一樣,不同之處在於,LinkedHashMap通過加入了雙向的鏈表結構來保存插入數據的順序。所以說是LinkedList和HashMap的結合體。
爲了保證迭代的順序,LinkedHashMap存儲了2份數據,一份是HashMap結構,一份是LinkedList的結構。迭代的時候使用LinkedList結構來迭代,保證順序。
LinkedHashMap繼承與HashMap,通過覆蓋一些方法和加入鏈表結構來完成自己的功能。
首先定義了鏈表結構類似的head 和last,標識鏈表的開頭和結尾,迭代的時候重頭開始迭代。
/**
* 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;
內部數據結構 Entry也加入了before和after來存儲前後引用。
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);
}
}
一切都和鏈表一樣,關於鏈表LinkedList,可以看我的另一篇 LinkedList。
三、存取和順序。
-
存儲方法
LinkedHashMap沒有覆蓋存儲put方法,調用的是HashMap的put方法(詳細看>>>HashMap詳解),這裏主要分析LinkedHashMap在存儲的時候,覆蓋了哪些動作。
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//初始化,put的時候初始化數組。
if ((tab = table) == null || (n = tab.length) == 0)
//初始化
n = (tab = resize()).length;
//計算hash值在數組中的index,如果該index不存在就創建newNode
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);//-----------------------------------1
else {
Node<K,V> e; K k;
//如果hash相同並且key也相同則覆蓋數據
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//是否是treeNode,treeNode是1.8爲了提高大容量Map的效率而加入的結構
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);------------------------2
//鏈表長度超過8 轉換鏈表爲紅黑樹進行存儲
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;
}
}
//如果key存在則覆蓋value返回oldValue
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);//----------------------------------------------3
return oldValue;
}
}
++modCount;
//是否需要擴容
if (++size > threshold)
resize();
afterNodeInsertion(evict);//-----------------------------------4
return null;
}
主要來看看代碼中標記的數字的含義,數字的地方是LinkedHashMap覆蓋的地方。
覆蓋newNode方法
1的位置是插入的key不存在是,創建一個節點。LinkedHashMap覆蓋了該方法,創建node,並且將node放在鏈表結尾。
2的位置Hash衝突的時候,當然最後要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;
}
linkNodeLast(p)方法的源碼
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;
}
}
afterNodeAccess()
3處是存在相同的key的時候,覆蓋原來的Value,然後調用afterNodeAccess(),HashMap的該方法是一個空方法,LinkedList覆蓋了它。該方法的作用是將節點移動到鏈表的末尾。該方法只會在存取的時候調用(put和get)。是否移動到末尾和設置的排序規則accessOrder有關。
void afterNodeAccess(Node<K,V> e) { // move node to last
LinkedHashMap.Entry<K,V> last;
//設置的排序規則有關。如果是按照插入順序,則不會將第二次插入的相同key移到最後。
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
accessOrder定義的是迭代時節點的獲取順序。
accessOrder爲fasle代表按照插入順序,重複插入相同key不改變順序。
accessOrder爲true代表按照存取順序,每次存取都會移動節點到末尾。
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);
}
}
possibly remove eldest: 可能刪除最舊的數據。
該方法主要是刪除head,但是需要 removeEldestEntry返回true。但是LinkedHashMap的該方法返回的永遠是false。
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return false;
}
該方法的作用是判斷什麼時候需要我們刪除node來減少內存。刪除的節點是不怎麼使用的節點。該方法需要我們自己覆蓋實現(如果有必要)。
這裏我們要引入一個概念:緩存淘汰算法(LRU)
緩存淘汰算法(LRU)
LRU(Least recently used,最近最少使用)算法根據數據的歷史訪問記錄來進行淘汰數據,其核心思想是“如果數據最近被訪問過,那麼將來被訪問的機率也更高”。在內存不足時可以淘汰最老的數據。
LinkedHashMap中,可以將最少訪問的node放在head(這是可行的)。所以LinkedHashMap可以實現 LRU。
LRU詳情,請查看LRU算法。
-
get方法
get方法 LinkedHashMap進行了覆蓋,比較簡單。加入了根據排序規則accessOrder的值來判斷是否移動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;
}
總結
1、 LinkedHashMap繼承與HashMap,是HashMap和LinkedList的結合體。
2、內部結構entry 繼承與HashMap.Entry,並且加入 before和After來支持鏈表操作。同時定義鏈表head和tail,用來實現鏈表的迭代。
3、默認的迭代順序是插入順序,重複插入不影響順序。通過設置accessOrder=true可以將迭代順序修改爲存取順序,每次存取,都會放在鏈表的末尾。改值只能通過構造方法設置。
4、LinkedHashMap可以實現LRU緩存淘汰算法,不過需要自己來實現。
如果對您有所幫助,請頂一下。