LinkedHashMap源碼分析 為什麼要有LinkedHashMap? 在分析HashMap的時候提到了HashMap是無序的,即添加節點的順序和遍歷的順序不一致 LinkedHashMap保證節點的順序,這也是LinkedHashMap和HashMap的主要區別 存儲示意圖 類結構 Linke ...
LinkedHashMap源碼分析
為什麼要有LinkedHashMap?
在分析HashMap的時候提到了HashMap是無序的,即添加節點的順序和遍歷的順序不一致
@Test
public void test1() {
HashMap<String,String> hashMap=new HashMap<String, String>();
hashMap.put("tom", "american");
hashMap.put("jack", "chainese");
hashMap.put("mary", "japanese");
Set<Entry<String, String>> entrySet = hashMap.entrySet();
Iterator<Entry<String, String>> iterator = entrySet.iterator();
while(iterator.hasNext()) {
Entry<String, String> entry = iterator.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+":"+value);
}
}
輸出:
tom:american
mary:japanese
jack:chainese
LinkedHashMap保證節點的順序,這也是LinkedHashMap和HashMap的主要區別
@Test
public void test2() {
LinkedHashMap<String,String> linkedHashMap=new LinkedHashMap();
linkedHashMap.put("tom", "american");
linkedHashMap.put("jack", "chainese");
linkedHashMap.put("mary", "japanese");
Set<Entry<String, String>> entrySet = linkedHashMap.entrySet();
Iterator<Entry<String, String>> iterator = entrySet.iterator();
while(iterator.hasNext()) {
Entry<String, String> entry = iterator.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+":"+value);
}
}
輸出:
tom:american
jack:chainese
mary:japanese
存儲示意圖
類結構
public class LinkedHashMap<K,V>
extends HashMap<K,V>
implements Map<K,V>
LinkedHashMap是HashMap的子類,它對HashMap做了一些增強
節點
static class Entry<K,V> extends HashMap.Node<K,V> {//LinkedHashMap的Entry節點是HashMap的Node節點的子類
Entry<K,V> before, after;//新增了before、after分別指向前驅和後繼
Entry(int hash, K key, V value, Node<K,V> next) {
//直接使用HashMap的Node節點構造方法
super(hash, key, value, next);
}
}
屬性
//頭指針指向第一個添加節點
transient LinkedHashMap.Entry<K,V> head;
//尾指針指向最後一個添加節點
transient LinkedHashMap.Entry<K,V> tail;
//排序規則,true的話按照訪問順序排序,最近訪問的放到最後,false也是預設按照插入順序排序
final boolean accessOrder;
構造方法
//指定初始化容量和載入因數
public LinkedHashMap(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
accessOrder = false;
}
//指定初始化容量
public LinkedHashMap(int initialCapacity) {
super(initialCapacity);
accessOrder = false;
}
//無參構造方法
public LinkedHashMap() {
super();
accessOrder = false;
}
//使用Map初始化
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;
}
方法
LinkedHashMap中並沒有put方法,所以使用的是父類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)
//當根據hash計算的下標位置沒放節點,調用LinkedHashMap的newNode方法
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;
}
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;
}
private void linkNodeLast(LinkedHashMap.Entry<K,V> p) {
//保存LinkedHashMap的為指針
LinkedHashMap.Entry<K,V> last = tail;
tail = p;
if (last == null)//尾指針為null說明LinkedHashMap中沒元素
head = p;
else {//有元素
//新節點的前驅指向添加之前的尾指針
p.before = last;
//添加之前的尾指針節點的後繼指向新節點
last.after = p;
}
}
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;
}
void afterNodeInsertion(boolean evict) { // possibly remove eldest
LinkedHashMap.Entry<K,V> first;
if (evict && (first = head) != null && removeEldestEntry(first)) {//removeEldestEntry方法返回false所以不會進入if
K key = first.key;
removeNode(hash(key), key, null, false, true);
}
}
get(Object)根據key獲取值
public V get(Object key) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) == null)//調用HashMap的方法拿到值
return null;
if (accessOrder)//如果是按照訪問順序排序的話
//訪問過後要修改順序
afterNodeAccess(e);
return e.value;
}
//把訪問的節點移動到鏈表的最末端
void afterNodeAccess(Node<K,V> e) {
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;
}
}
remove(Object)方法是調用父類HashMap的方法
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
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 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
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;
//調用LinkedHashMap·的方法來實現雙鏈的刪除
afterNodeRemoval(node);
return node;
}
}
return null;
}
void afterNodeRemoval(Node<K,V> e) { // unlink
LinkedHashMap.Entry<K,V> p =
(LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
//把要移除節點的前驅後繼置為null
p.before = p.after = null;
if (b == null)//b為null即移除的就是第一個元素
//頭指針指向移除元素的後繼
head = a;
else
b.after = a;
if (a == null)//a為null即移除的元素是最後一個元素
//尾指針指向移除元素的前驅
tail = b;
else
a.before = b;
}