一般来说HashMap的存取顺序是不一致的,比如说:
@Test public void test(){ HashMap<String, String>map=new HashMap<String, String>(); map.put("1", "111"); map.put("2", "122"); map.put("3", "133"); map.put("4", "144"); map.put("5", "155"); for(String str:map.keySet()){ System.out.println("key is "+str+" value is "+map.get(str)); } }
输出的结果是:
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>(); linkedHashMap.put("1", "111"); linkedHashMap.put("2", "222"); linkedHashMap.put("3", "333"); linkedHashMap.put("4", "444"); linkedHashMap.put("5", "555"); for(String str:linkedHashMap.keySet()){ System.out.println("key is "+str+" value is "+linkedHashMap.get(str)); }
输出结果:
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>(); map.put("1", "1111"); map.put("2", "2222"); map.put("3", "3333"); map.put("4", "4444"); map.put("5", "5555"); for(String str:map.keySet()){ System.out.println("key is "+str+" value is "+map.get(str)); }
输出结果
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
© 著作权归作者所有
文章评论(0)