了解java中的acessOrder LinkedHashMap实现

nan*_*oft 5 java hashmap linkedhashmap

据我所知,LinkedHashMap扩展了HashMap,LinkedHashMap.Entry也扩展了HashMap.Entry.

LinkedHashMap有两个主要属性:1)headerLinkedHashMap.Entry节点.2)继承的 HashMap.Entry []数组.现在,中的LinkedHashMap被分配的阵列LinkedHashMap.Entry在运行时,这是由下面方法照顾:

/**
     * This override differs from addEntry in that it doesn't resize the
     * table or remove the eldest entry.
     */
    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);
        table[bucketIndex] = e;
        e.addBefore(header);
        size++;
    }
Run Code Online (Sandbox Code Playgroud)

前三行的方法实际上转换HashMap.EntryLinkedHashMap.Entry和还保持的引用之后之前的输入的方式,使得之前指向最后一个元素,以便和最后一个元素的指向形成圆圈.

现在,当我们创建任一Maps的实例(使用新的构造函数)时,没有为table属性分配内存,因为它刚刚初始化为空表.

Map<String, String> linkedHashMap = new LinkedHashMap<String, String>();
Run Code Online (Sandbox Code Playgroud)

现在让我们说我们做的是: -

linkedHashMap.put("a", "A");
linkedHashMap.put("b", "B");
linkedHashMap.put("c", "C");
Run Code Online (Sandbox Code Playgroud)

在这些语句之后,我们的LinkedHashMap数据结构(表格数组在第一次放置之后被初始化)看起来像在pic.I中标记了元素a,b和c以便于参考.我明白真正的顺序不一样.我发现这个数据结构非常复杂 - 这么多参考文献.它具有完全不同的双链表,并且用于不同的目的,也是普通hashmap的单链表,并且在同一Entry中也是如此.我的理解是否正确?

在此输入图像描述

SDe*_*kov 4

您已经对代码进行了一些很好的挖掘,这太棒了!然而 LinkedHashMap 并不像您想要的那么复杂。它实际上是 HashMap 的一个非常简单的扩展,其唯一目的是保留元素添加的顺序\xe2\x80\xa0

\n\n
\n

该方法的前三行实际上将HashMap.Entry转换为LinkedHashMap.Entry,并且还维护了 Entry 的 after 和 before 的引用

\n
\n\n

这是正确的,LinkedHashMap.Entry扩展了 HashMap.Entry ,但通过存储指向和条目的指针来添加链接位。beforeafter

\n\n

哈希映射

\n\n

在此输入图像描述

\n\n

链接哈希映射

\n\n

在此输入图像描述

\n\n

尽管LinkedHashMap图看起来复杂得多,但它只是添加了蓝色/红色箭头表示的before和指针。after

\n\n

\xe2\x80\xa0除了插入顺序之外,LinkedHashMap 还支持访问顺序(排序模式)作为构造函数参数。如果标志设置为true迭代列表,则将按照元素被访问的顺序而不是插入的顺序返回元素。

\n\n

图片来自JavaArticles

\n