• 发表于 5个月前
• 阅读 8
• 收藏 0
• 评论 0

• LinkedHashMap`继承`HashMap，`put`调用`HashMap``put`，区别在于`HashMap单向链表``LinkedHashMap双向链表`
``````//hashMap
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
......
}
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);
}
}
``````
• `hashMap.add - > LinkedHashMap.newNode`，构造`LinkHashMap.Node`双向链表节点包装`HashMap.Node`
``````//持有头节点
//尾节点
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> newNode(int hash, K key, V value, Node<K,V> e) {
return p;
}
tail = p;
if (last == null)
else {
p.before = last;
last.after = p;
}
}
``````
``````//正常插入，遍历有序
public V get(Object key) {
Node<K,V> e;
//HashMap.getNode
if ((e = getNode(hash(key), key)) == null)
return null;
if (accessOrder)
afterNodeAccess(e);
return e.value;
}
//移动节点到到尾，改变链表结构，耗性能
void afterNodeAccess(Node<K,V> e) { // move node to last
if (accessOrder && (last = tail) != e) {
(LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
p.after = null;
if (b == null)
else
b.after = a;
if (a != null)
a.before = b;
else
last = b;
if (last == null)
else {
p.before = last;
last.after = p;
}
tail = p;
++modCount;
}
}
``````

×