- LinkedHashMap可以認為是HashMap+LinkedList
- LinkedHashMap的基本實現思想就是----多態(tài)
- LinkedHashMap extends HashMap implements Map
- LinkedList是有序的,accessOrder為true每次訪問一個元素(get或put)瘤缩,被訪問的元素都被提到最后面去了
//重寫hashmap方法(每當新建節(jié)點添加先后關系)
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;
}
//插入最后節(jié)點
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;
}
}
// 節(jié)點添加完后
void afterNodeAccess(Node<K,V> e) { // move node to last
LinkedHashMap.Entry<K,V> last;
//是accessorder(lru)則繼續(xù)(putval執(zhí)行則當前最后節(jié)點爹梁,不需重復添加)
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;
}
}
//本身初始結構担锤,其他內容繼承
transient LinkedHashMap.Entry<K,V> head;
transient LinkedHashMap.Entry<K,V> tail;
//true lru false插入順序
final boolean accessOrder;
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);
}
}
Entry<K,V>繼承hashmap真實屬性如下:
- K key
- V value
- Entry<K, V> next
- int hash
- Entry<K, V> before
- Entry<K, V> after