美文网首页
基础知识(二) LinkedHashMap 源码详解

基础知识(二) LinkedHashMap 源码详解

作者: 架构技术专栏 | 来源:发表于2017-03-20 13:09 被阅读22次

    知识点

    继承于HashMap 实现于Map接口
    public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>

    LinkedHashMap 继承了 HashMap 最主要的区别就是有序。内部使用散列链表 红黑树实现。注意此Map不是线程安全的,如果需要同步使用请使用ConcurrentHashMap 或者 Collections.synchronizedMap。

    其实它内部使用的还是HashMap的方法,主要区别在以下三个方法中。节点访问后、节点插入后、节点移除后做一些事情。
    void afterNodeAccess(Node<K,V> p) { }
    void afterNodeInsertion(boolean evict) { }
    void afterNodeRemoval(Node<K,V> p) { }

    常量参数

    很多常量用的都是他爸的

    //继承了HashMap Node 内部定义两个参数 
    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);
            }
        }
    
    

    transient LinkedHashMap.Entry<K,V> head; //双向链表的头对象数据
    transient LinkedHashMap.Entry<K,V> tail; //双向链表的尾对象数据

    源码解析

    //其实就是一个移动链表的过程
     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;
            }
        }
    

    相关文章

      网友评论

          本文标题:基础知识(二) LinkedHashMap 源码详解

          本文链接:https://www.haomeiwen.com/subject/dfbbnttx.html