LinkedHashMap 在 Map 集合框架的位置
LinkedHashMap简介
LinkedHashMap是Map 接口的 哈希表(hash table) 和 链表(linked list) 的实现,具有可预测的迭代顺序。此实现与 HashMap 的不同之处在于,它维护一个双链接列表,该列表贯穿其所有条目。这个链表定义了迭代的顺序,通常是键值插入到 map 中的插入顺序(insertion-order). 请注意,如果键重新插入到 map 中,则插入顺序不受影响。
在遍历LinkedHashMap时,不会像遍历 HashMap 和 Hashtable 所得到的遍历顺序是不确定的。而且LinkedHashMap在遍历有顺序保证的同时,不会像TreeMap那样招致额外的开销。它可以用来拷贝已有的map, 不用考虑这个被拷贝的map对象原来的实现方式。拷贝出来的map对象和原始的map对象的顺序是一致的。
void foo(Map m) {
Map copy = new LinkedHashMap(m);
...
}
写一个测试方法跑一下看下结果:
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class LinkedHashMapTest {
public static void main(String args[]) {
Map<Integer, Integer> map = new HashMap();
for(int i=1; i<5; i++) {
map.put(i, i*i);
}
for(int i=1; i>-5; i--) {
map.put(i, i*i);
}
System.out.println(map);
System.out.println(map);
System.out.println(map);
System.out.println("-----------------copy from map -----------------------");
LinkedHashMap<Integer,Integer> copy = new LinkedHashMap<Integer, Integer>(map);
System.out.println(copy);
Map<Integer, Integer> linkedHashMap = new LinkedHashMap();
for(int i=1; i<5; i++) {
linkedHashMap.put(i, i*i);
}
for(int i=1; i>-5; i--) {
linkedHashMap.put(i, i*i);
}
System.out.println("-----------------------------------------");
System.out.println(linkedHashMap);
System.out.println("---------- put exist key again ---------------------");
for(int i=1; i<5; i++) {
linkedHashMap.put(i, i*i);
}
System.out.println(linkedHashMap);
System.out.println("--- remove exist key and put again, keep insert order ----");
linkedHashMap.remove(3);
linkedHashMap.put(3, 9);
System.out.println(linkedHashMap);
}
}
输出内容:
{
0=0, -1=1, 1=1, -2=4, 2=4, -3=9, 3=9, -4=16, 4=16}
{
0