LinkedHashMap 底层分析(下)

简介: 众所周知 HashMap 是一个无序的 Map,因为每次根据 key 的 hashcode 映射到 Entry 数组上,所以遍历出来的顺序并不是写入的顺序。

构造方法


LinkedHashMap 的构造方法:


public LinkedHashMap() {
        super();
        accessOrder = false;
    }


其实就是调用的 HashMap 的构造方法:


HashMap 实现:


public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        threshold = initialCapacity;
        //HashMap 只是定义了改方法,具体实现交给了 LinkedHashMap
        init();
    }


可以看到里面有一个空的 init(),具体是由 LinkedHashMap 来实现的:


@Override
    void init() {
        header = new Entry<>(-1, null, null, null);
        header.before = header.after = header;
    }


其实也就是对 header 进行了初始化。


put 方法


LinkedHashMapput() 方法之前先看看 HashMapput 方法:


public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key);
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                //空实现,交给 LinkedHashMap 自己实现
                e.recordAccess(this);
                return oldValue;
            }
        }
        modCount++;
        // LinkedHashMap 对其重写
        addEntry(hash, key, value, i);
        return null;
    }
    // LinkedHashMap 对其重写
    void addEntry(int hash, K key, V value, int bucketIndex) {
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }
        createEntry(hash, key, value, bucketIndex);
    }
    // LinkedHashMap 对其重写
    void createEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
    }       


主体的实现都是借助于 HashMap 来完成的,只是对其中的 recordAccess(), addEntry(), createEntry() 进行了重写。


LinkedHashMap 的实现:


//就是判断是否是根据访问顺序排序,如果是则需要将当前这个 Entry 移动到链表的末尾
        void recordAccess(HashMap<K,V> m) {
            LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
            if (lm.accessOrder) {
                lm.modCount++;
                remove();
                addBefore(lm.header);
            }
        }
    //调用了 HashMap 的实现,并判断是否需要删除最少使用的 Entry(默认不删除)    
    void addEntry(int hash, K key, V value, int bucketIndex) {
        super.addEntry(hash, key, value, bucketIndex);
        // Remove eldest entry if instructed
        Entry<K,V> eldest = header.after;
        if (removeEldestEntry(eldest)) {
            removeEntryForKey(eldest.key);
        }
    }
    void createEntry(int hash, K key, V value, int bucketIndex) {
        HashMap.Entry<K,V> old = table[bucketIndex];
        Entry<K,V> e = new Entry<>(hash, key, value, old);
        //就多了这一步,将新增的 Entry 加入到 header 双向链表中
        table[bucketIndex] = e;
        e.addBefore(header);
        size++;
    }
        //写入到双向链表中
        private void addBefore(Entry<K,V> existingEntry) {
            after  = existingEntry;
            before = existingEntry.before;
            before.after = this;
            after.before = this;
        }  


get 方法


LinkedHashMap 的 get() 方法也重写了:


public V get(Object key) {
        Entry<K,V> e = (Entry<K,V>)getEntry(key);
        if (e == null)
            return null;
        //多了一个判断是否是按照访问顺序排序,是则将当前的 Entry 移动到链表头部。    
        e.recordAccess(this);
        return e.value;
    }
    void recordAccess(HashMap<K,V> m) {
        LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
        if (lm.accessOrder) {
            lm.modCount++;
            //删除
            remove();
            //添加到头部
            addBefore(lm.header);
        }
    }


clear() 清空就要比较简单了:


//只需要把指针都指向自己即可,原本那些 Entry 没有引用之后就会被 JVM 自动回收。
    public void clear() {
        super.clear();
        header.before = header.after = header;
    }


总结


总的来说 LinkedHashMap 其实就是对 HashMap 进行了拓展,使用了双向链表来保证了顺序性。


因为是继承与 HashMap 的,所以一些 HashMap 存在的问题 LinkedHashMap 也会存在,比如不支持并发等。


相关文章
|
存储 算法 Java
HashMap 之底层数据结构和扩容机制
HashMap 之底层数据结构和扩容机制
775 1
|
存储 算法 安全
HashMap底层实现原理
HashMap底层实现原理
146 0
|
4月前
|
存储 安全 容器
ConcurrentHashMap底层详解
ConcurrentHashMap底层详解
110 2
ConcurrentHashMap底层详解
|
存储 安全 Java
HashMap底层结构、扩容机制实战探索
HashMap底层结构、扩容机制实战探索
HashMap底层结构、扩容机制实战探索
|
5月前
|
存储 Java
【JDK 源码分析】HashMap 底层结构
【1月更文挑战第27天】【JDK 源码分析】HashMap 底层结构
|
5月前
|
存储 安全
ConcurrentHashMap 底层具体实现
ConcurrentHashMap 底层具体实现
|
5月前
|
存储 安全 Java
Hashtable和HashMap:差异,数据结构概述,以及JDK的影响
Hashtable和HashMap:差异,数据结构概述,以及JDK的影响
44 0
|
存储
ArrayList底层结构和源码分析
ArrayList底层结构和源码分析
104 1
ArrayList底层结构和源码分析
|
算法 安全 Java
数据结构之PriorityQueue源码及特性分析 (大小根堆转换、扩容)
数据结构之PriorityQueue源码及特性分析 (大小根堆转换、扩容)
数据结构之PriorityQueue源码及特性分析 (大小根堆转换、扩容)
|
存储 算法
【HashMap底层运行原理】
【HashMap底层运行原理】