如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
,您指定要使用“访问顺序”映射,而不是“插入顺序”映射。这意味着您将按访问顺序(首先从最近访问)获得值。
您的
get
和put
调用均构成“访问”。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/