一般来说HashMap的存取顺序是不一致的,比如说:
@Test
2
public void test(){
3
HashMap<String, String>map=new HashMap<String, String>();
4
map.put("1", "111");
5
map.put("2", "122");
6
map.put("3", "133");
7
map.put("4", "144");
8
map.put("5", "155");
9
for(String str:map.keySet()){
10
System.out.println("key is "+str+" value is "+map.get(str));
11
}
12
}
输出的结果是:
key is 3 value is 133
key is 2 value is 122
key is 1 value is 111
key is 5 value is 155
key is 4 value is 144
也就是说不能保证取出数据的顺序和存入时一样,但是LinkedHashMap可以做到这点
LinkedHashMap<String, String>linkedHashMap=new LinkedHashMap<String, String>();
2
linkedHashMap.put("1", "111");
3
linkedHashMap.put("2", "222");
4
linkedHashMap.put("3", "333");
5
linkedHashMap.put("4", "444");
6
linkedHashMap.put("5", "555");
7
for(String str:linkedHashMap.keySet()){
8
System.out.println("key is "+str+" value is "+linkedHashMap.get(str));
9
}
输出结果:
key is 1 value is 111
key is 2 value is 222
key is 3 value is 333
key is 4 value is 444
key is 5 value is 555
TreeMap也可以做到
TreeMap<String, String>map=new TreeMap<String, String>();
2
map.put("1", "1111");
3
map.put("2", "2222");
4
map.put("3", "3333");
5
map.put("4", "4444");
6
map.put("5", "5555");
7
for(String str:map.keySet()){
8
System.out.println("key is "+str+" value is "+map.get(str));
9
}
输出结果
key is 1 value is 1111
key is 2 value is 2222
key is 3 value is 3333
key is 4 value is 4444
key is 5 value is 5555