代码:
//hashmap不保证插入元素的顺序
Map hashmap = new HashMap<String,Object>();hashmap.put("1", 1);
hashmap.put("2", 2);
hashmap.put("3", 3);
hashmap.put("4", 4);
System.out.println("hashmap:"+hashmap);
//linkedhashmap:保证插入元素的顺序
Map linkedmap = new LinkedHashMap<String,Object>();
linkedmap.put("1", 1);
linkedmap.put("2", 2);
linkedmap.put("3", 3);
linkedmap.put("4", 4);
System.out.println("linkedmap:"+linkedmap);
//不保证插入元素的顺序,但会按照key值排序
Map treemap = new TreeMap<String,Object>();
treemap.put("1", 1);
treemap.put("2", 2);
treemap.put("3", 3);
treemap.put("4", 4);
System.out.println("treemap:"+treemap);
输出:
hashmap:{3=3, 2=2, 1=1, 4=4}
linkedmap:{1=1, 2=2, 3=3, 4=4}
treemap:{1=1, 2=2, 3=3, 4=4}