天天看点

源码看JAVA【二十三】LinkedHashMap

public class LinkedHashMap<K,V>

    extends HashMap<K,V>

    implements Map<K,V>

1、继承了HashMap,对HashMap的一个补充,LinkedHashMap添加了元素是有序的存储,具体的实现下面会详细介绍

2、内部类Entry继承了HashMap的Node,添加了前一个元素和后一个元素,为顺序打好基础。

/**
     * HashMap.Node subclass for normal LinkedHashMap entries.
     */
    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);
        }
    }
           

3、插入、删除

创建新节点就会在当前链表中在最后添加元素:linkNodeLast

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;
    }
           

每次HashMap删除节点都会进行如下操作,LinkedMap同时删除相应的元素。

void afterNodeRemoval(Node<K,V> e) { // unlink
        LinkedHashMap.Entry<K,V> p =
            (LinkedHashMap.Entry<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;
    }
           

总结:LinkedHashMap实际是通过增加了entry的存储,并添加before与after节点实现HashMap的有序化。

继续阅读