LinkedHashMap源碼簡讀
1、LinkedHashMap繼承自HashMap,HashMap具有的特性它都具有。
2、實(shí)際上,LinkedHashMap是通過雙向鏈表和散列表這兩種數(shù)據(jù)組合實(shí)現(xiàn)的。LinkedHashMap中的“Linked”實(shí)際上指的是雙向鏈表,并非指“用鏈表法解決散列沖突”。
3、LinkedHashMap不僅支持按照插入順序遍歷數(shù)據(jù),還支持按照訪問順序來遍歷數(shù)據(jù)。通過設(shè)置accessOrder屬性為true即可。也就是說它本身就是一個支持LRU緩存淘汰策略的緩存系統(tǒng)。
查詢、插入、刪除方法。
LinkedHashMap繼承自HashMap,而HashMap是用散列表實(shí)現(xiàn)的,所以LinkedHashMap在HashMap的基礎(chǔ)上增加了雙向鏈表來存儲數(shù)據(jù)。那么是在哪兒添加的呢?我們對get、put、remove三個方法逐個分析。
首先LinkedHashMap中關(guān)于雙向鏈表的變量定義:
/**
* The head (eldest) of the doubly linked list.
*/
transient LinkedHashMapEntry<K,V> head;
/**
* The tail (youngest) of the doubly linked list.
*/
transient LinkedHashMapEntry<K,V> tail;
LinkedHashMap#get(Object key)方法
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;
}
LinkedHashMap重寫了HashMap中的get(Object key)方法,主要就是增加了accessOrder相關(guān)操作。核心的查找操作還是通過HashMap中的方法去進(jìn)行。
LinkedHashMap#put(K key, V value)方法
LinkedHashMap完全繼承了HasMap的get(K key, V value)方法,沒有做任何修改,那么是它是如何將新增的數(shù)據(jù)也添加進(jìn)雙向鏈表中呢?
HashMap中,put方法調(diào)用了putVal方法,代碼如下:
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)
// 注釋一
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
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;
}
如上所示,HashMap在插入數(shù)據(jù)時,會先去查找該數(shù)據(jù)是否已存在。如果不存在,就調(diào)用newNode方法來創(chuàng)建新元素;如果存在,就進(jìn)行相應(yīng)的處理,同時調(diào)用afterNodeAccess方法。需要注意的是newNode和afterNodeAccess均已被LinkedHashMap重寫,做了額外的工作,來講數(shù)據(jù)添加進(jìn)雙向鏈表里面。
下面針對細(xì)節(jié)進(jìn)行解釋:
注釋一:
這里新生成了一個node,然后將其插入到數(shù)組中。
另外newNode方法被LinkedHashMap重寫了,它在new的同時,還將node添加進(jìn)了雙向鏈表。
LinkedHashMap#newNode():
Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
LinkedHashMapEntry<K,V> p =
new LinkedHashMapEntry<K,V>(hash, key, value, e);
linkNodeLast(p);
return p;
}
LinkedHashMap#linkNodeLast():將node鏈接到雙向鏈表尾部。
// link at the end of list
private void linkNodeLast(LinkedHashMapEntry<K,V> p) {
LinkedHashMapEntry<K,V> last = tail;
tail = p;
if (last == null)
head = p;
else {
p.before = last;
last.after = p;
}
}
注釋二:操作同上。
注釋三:
先看下HashMap中afterNodeAccess方法的定義,注釋寫的很明白,下面三個方法是專門讓LinkedHashMap去重寫的。
// Callbacks to allow LinkedHashMap post-actions
void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node<K,V> p) { }
那我們來看下LinkedHashMap中的afterNodeAccess方法:將node移動到鏈表結(jié)尾。
void afterNodeAccess(Node<K,V> e) { // move node to last
LinkedHashMapEntry<K,V> last;
if (accessOrder && (last = tail) != e) {
LinkedHashMapEntry<K,V> p =
(LinkedHashMapEntry<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;
}
}
LinkedHashMap#remove(Object key)方法
LinkedHashMap也是繼承自
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
LinkedHashMap#removeNode方法:
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;
if ((tab = table) != null && (n = tab.length) > 0 &&
...
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
...
afterNodeRemoval(node);
return node;
}
}
return null;
}
可以看到,刪除時調(diào)用了afterNodeRemoval方法,這個方法在HashMap中是空實(shí)現(xiàn),在LinkedHashMap中被重寫。
LinkedHashMap#afterNodeRemoval方法:將node元素從雙向鏈表中移除。
void afterNodeRemoval(Node<K,V> e) { // unlink
LinkedHashMapEntry<K,V> p =
(LinkedHashMapEntry<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;
}
總結(jié):
HashMap底層是用數(shù)組來實(shí)現(xiàn)的,利用散列表我們可以實(shí)現(xiàn)快速訪問、存取元素,但是元素的順序得不到保障。
LinkedHashMap在HashMap的基礎(chǔ)上,將元素添加進(jìn)了雙向鏈表中,所以可以在快速訪問、存取元素的同時,還可以保證元素的順序。
另外,LinkedHashMap天生就是一個支持LRU緩存淘汰策略的緩存系統(tǒng)。