JAVA非并发容器--LinkedHashMap

概述

LinkedHashMap与HashMap的最大区别是:LinkedHashMap的迭代器遍历顺序与put元素的顺序是一致的。

Entry结构

private static class Entry extends HashMap.Entry {
        // These fields comprise the doubly linked list used for iteration.
        Entry before, after;

        Entry(int hash, K key, V value, HashMap.Entry next) {
            super(hash, key, value, next);
        }

        /**
         * Removes this entry from the linked list.
         */
        private void remove() {
            before.after = after;
            after.before = before;
        }

        /**
         * Inserts this entry before the specified existing entry in the list.
         */
        private void addBefore(Entry existingEntry) {
            after  = existingEntry;
            before = existingEntry.before;
            before.after = this;
            after.before = this;
        }

        /**
         * This method is invoked by the superclass whenever the value
         * of a pre-existing entry is read by Map.get or modified by Map.set.
         * If the enclosing Map is access-ordered, it moves the entry
         * to the end of the list; otherwise, it does nothing.
         */
        void recordAccess(HashMap m) {
            LinkedHashMap lm = (LinkedHashMap)m;
            if (lm.accessOrder) {
                lm.modCount++;
                remove();
                addBefore(lm.header);
            }
        }

        void recordRemoval(HashMap m) {
            remove();
        }
    }

从代码中可以看出,Entry在HashMap.Entry的基础上增加了两个指针,从而构成双向链表。
存储结构如下:


JAVA非并发容器--LinkedHashMap_第1张图片
linkedHashmap.png

你可能感兴趣的:(JAVA非并发容器--LinkedHashMap)