hashmap - LinkedHashMap的排序

标签 hashmap linkedhashmap

如javadoc中为LinkedHashMap指定的那样,如果将 key 重新插入到映射中,则插入顺序不会受到影响,但是在运行以下程序时,我注意到在更改访问顺序时再次插入相同的 key 。

Map<Integer, String> map = new LinkedHashMap<Integer,String>(16, .75f, true);
    map.put(new Integer(1), "Ajay");
    map.put(new Integer(2), "Vijay");
    map.put(new Integer(3), "Kiran");
    map.put(new Integer(4), "Faiz");

    for(String value:map.values()){
        System.out.println(value);
    }

    String val =map.get(new Integer(3));
    map.put(new Integer(2), "Ravi");
    System.out.println("After changes...");
    for(String value:map.values()){
        System.out.println(value);
    }

在运行上面的程序时,我得到如下的o/p:
Ajay
Vijay
Kiran
Faiz
After changes...
Ajay
Faiz
Kiran
Ravi

当我重新插入使用的 key 2时,为何更改了访问顺序。

请帮助我了解操作说明。

谢谢,

最佳答案

new LinkedHashMap<Integer,String>(16, .75f, true);

使用该true,您指定要使用“访问顺序”映射,而不是“插入顺序”映射。

这意味着您将按访问顺序(首先从最近访问)获得值。

您的getput调用均构成“访问”。

A special constructor is provided to create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently (access-order). This kind of map is well-suited to building LRU caches. Invoking the put or get method results in an access to the corresponding entry (assuming it exists after the invocation completes).

关于hashmap - LinkedHashMap的排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35838739/

相关文章:

java - 如何遍历Hashmap中的对象

java - Perl 中的链接 HashMap

java LRU缓存: LinkedHashMap with a timestamp?

java - LinkedHashMap中为什么需要hashcode和bucket

java - LinkedHashMap 内存消耗

java - Hashmap 不适用于 int、char

java - 如何在迭代 HashMap 时删除另一项(不是您持有的项)

c++ - 使用动态分配的数组创建哈希表?

java - 如何验证HashMap中的值是否存在

Java 使用部分键从 LinkedHashMap 获取值