我正在尝试HashMap使用LinkedHashMapand对输出进行排序TreeMap。
当我TreeMap用来整理HashMap它时,它就像一种魅力。
Map<Integer, String> hMap = new HashMap<Integer, String>();
hMap.put(40, "d");
hMap.put(10, "a");
hMap.put(30, "c");
hMap.put(20, "b");
System.out.println(" ");
System.out.println("before");
for (Map.Entry m1 : hMap.entrySet()) {
System.out.print(m1.getKey() + " " + m1.getValue() + " ");
}
System.out.println("after");
Map<Integer, String> hTree = new TreeMap<Integer, String>(hMap);
for (Map.Entry m2 : hTree.entrySet()) {
System.out.print(m2.getKey() + " " + m2.getValue() + " ");
}
输出 :
before
20 b 40 d 10 a 30 c
after
10 a 20 b 30 c 40 d
但是当我尝试LinkedHashMap排序时,HashMap它似乎不起作用。
Map<Integer, String> hMap = new HashMap<Integer, String>();
hMap.put(10, "a");
hMap.put(20, "b");
hMap.put(30, "c");
hMap.put(40, "d");
System.out.println("before");
for (Map.Entry m1 : hMap.entrySet()) {
System.out.print(m1.getKey() + " " + m1.getValue() + " ");
}
System.out.println(" ");
System.out.println("after");
LinkedHashMap<Integer, String> lhMap = new LinkedHashMap<Integer, String>(hMap);
Iterator it = lhMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry me = (Map.Entry) it.next();
System.out.print(me.getKey() + " " + me.getValue()+" ");
}
输出 :
before
20 b 40 d 10 a 30 c
after
20 b 40 d 10 a 30 c
谁能告诉我为什么这种排序不起作用?那是因为LinkedHashMap正在过滤HashMap吗?
如果是为什么TreeMap对那个问题免疫?
相关分类