LinkedHashMap 排序
LinkedHashMap ordering
正如 LinkedHashMap 的 javadoc 中所指定的,如果将键重新插入到映射中,插入顺序不会受到影响但是 运行 下面的程序,我注意到在更改时再次插入相同的键访问顺序。
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
当我重新插入密钥 2 时,为什么它的访问顺序发生了变化。
请帮助我理解o/p。
谢谢,
new LinkedHashMap<Integer,String>(16, .75f, true);
在 true
中,您指定需要 "access-ordered" 地图,而不是 "insertion-ordered" 地图。
这意味着您将按照访问顺序获取值(最近最少访问最先)。
您的 get
和 put
通话都构成了 "access"。
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).
正如 LinkedHashMap 的 javadoc 中所指定的,如果将键重新插入到映射中,插入顺序不会受到影响但是 运行 下面的程序,我注意到在更改时再次插入相同的键访问顺序。
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
当我重新插入密钥 2 时,为什么它的访问顺序发生了变化。
请帮助我理解o/p。
谢谢,
new LinkedHashMap<Integer,String>(16, .75f, true);
在 true
中,您指定需要 "access-ordered" 地图,而不是 "insertion-ordered" 地图。
这意味着您将按照访问顺序获取值(最近最少访问最先)。
您的 get
和 put
通话都构成了 "access"。
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).