LinkedHashMap的实现原理

内部组成

LinkedHashMap继承了HashMap,内部增加了如下实例变量:

transient LinkedHashMap.Entry<K,V> head;

transient LinkedHashMap.Entry<K,V> tail;

final boolean accessOrder;

accessOrder表示按访问顺序还是插入顺序。header表示双向链表的头,tail表示双向链表的尾,它们的类型Entry是一个内部类,这个类继承了HashMap.Entry类,增加了两个变量:Entry<K,V> before, after; 指向链表中的前驱和后继。
Entry的完成定义:

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

无参构造


    public LinkedHashMap() {
        super(); // 调用HashMap的无参构造
        accessOrder = false; // 为false说明按照插入排序,为true说明按照访问排序,下面会详细介绍
    }

put

LinkedHashMap没有自己的put方法,所以调用的是父类HashMap的put方法,不同之处在于LinkedHashMap实现了afterNodeAccess和afterNodeInsertion方法
afterNodeAccess用于将节点放到链表的最后
afterNodeInsertion用于判断并删除最久未被访问的节点

HashMap的put方法

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
  	/**
     * Implements Map.put and related methods.
     *
     * @param hash hash for key // key 的哈希值
     * @param key the key 
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value // 如果为true则不改变已经存在的值
     * @param evict if false, the table is in creation mode. // 不清楚干啥的
     * @return previous value, or null if none // 旧值,key对应的值不存在时返回null
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        // tab为map的Node数组
        // n为数组的大小
        // i为key对应的Node数组下标
        // p为key对应的Node节点
        // PS:Node是一个单向链表
        if ((tab = table) == null || (n = tab.length) == 0) // 如果map为空
            n = (tab = resize()).length; // resize()方法初始化或加倍,Node数组的大小
        if ((p = tab[i = (n - 1) & hash]) == null) // (n - 1) & hash 得到key对应的Node数组下标,并赋值给i;
            tab[i] = newNode(hash, key, value, null); // 如果key对应的Node为null则创建常规(非树)节点,LinkedHashMap中复写了该方法
        else {
            Node<K,V> e; K k;
            // k为p的key
            // e表示key对应的Node对象
            // 下面这一堆if用来查找key对应的Node对象e
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k)))) // p的哈希值==key的hash值且[当前Node的key==key或(key不为空且key   equals  当前节点的key)]
                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——存在key对应的Node对象
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e); // HashMap中该方法的实现为空,作为LinkedHashMap的回调,将节点移动到最后
                return oldValue;
            }
        }
        ++modCount; // 修改次数
        if (++size > threshold) // size大于等于threshold(阈值)时,调用resize进行扩容
            resize();
        afterNodeInsertion(evict); // HashMap中该方法的实现为空,作为LinkedHashMap的回调,用来判断是否需要删除最久未被访问的节点,需要的话则删除
        return null;
    }

LinkedHashMap中的实现:



    void afterNodeInsertion(boolean evict) { // possibly remove eldest:可能会删除最年长的
        LinkedHashMap.Entry<K,V> first;
        // removeEldestEntry应用可查看另一篇文章:https://blog.csdn.net/wang_8101/article/details/89111314
        if (evict && (first = head) != null && removeEldestEntry(first)) { // removeEldestEntry方法用于判断是否删除最老的元素,LinkedHashMap中默认返回false,即不删除。LinkedHashMap的子类可以重写该方法用于删除最久未被访问的元素
            K key = first.key;
            removeNode(hash(key), key, null, false, true); // 删除节点,详解可查看:https://blog.csdn.net/wang_8101/article/details/88428566
        }
    }

    void afterNodeAccess(Node<K,V> e) { // move node to last:将节点移动到最后
        LinkedHashMap.Entry<K,V> last;
        if (accessOrder && (last = tail) != e) { // accessOrder 为true才会运行下面的代码
            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;
        }
    }

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

get

    public V get(Object key) {
        Node<K,V> e;
        if ((e = getNode(hash(key), key)) == null) // 调用HashMap的getNode方法
            return null;
        if (accessOrder) // 当根据访问顺序排序时,将节点放到双向链表最后
            afterNodeAccess(e);
        return e.value;
    }

小结:

LinkedHashMap是HashMap的子类,它的节点类:LinkedHashMap.Entry是HashMap.Node的子类,LinkedHashMap内部维护了一个单独的双向链表,每个节点既位于哈希表中,又位于双向链表中,在链表中的默认排序是插入顺序,也可以配置为按照访问顺序;
LinkedHashMap重写了部分方法来维护双向链表。
按插入排序经常用于处理键值对的数据,且保持其输入顺序,也回用于键已经排好序的场景,此种场景下,相比TreeMap他的效率更高
按照访问顺序经常用于缓存的实现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值