HashMap 实际上是一个链表的数组。HashMap 的一个功能缺点是它的无序性,被存入到 HashMap 中的元素,在遍历 HashMap 时,其输出是无序的。如果希望元素保持输入的顺序,可以使用 LinkedHashMap 替代。
LinkedHashMap继承自HashMap,具有高效性,同时在HashMap的基础上,又在内部增加了一个链表,用以存放元素的顺序。LinkedHashMap内部多了一个双向循环链表的维护,该链表是有序的,可以按元素插入顺序或元素最近访问顺序(LRU)排列,简单地说:LinkedHashMap=散列表+循环双向链表
LinkedHashMap 是根据元素增加或者访问的先后顺序进行排序,TreeMap 则是基于元素的固有顺序 (由 Comparator 或者 Comparable 确定)。而 TreeMap 则根据元素的 Key 进行排序。
1public class TreeMapTest { 2 3 public static void main(String args[]){ 4 5 Map<String, Integer> hashMap = new HashMap<>(); 6 System.out.println("hashmap結果"); 7 8 hashMap.put("1", 1); 9 hashMap.put("3", 3); 10 hashMap.put("7", 2); 11 hashMap.put("2", 7); 12 hashMap.put("4", 4); 13 Iterator iterator =hashMap.keySet().iterator(); 14 while (iterator.hasNext()) { 15 Object key= iterator.next(); 16 System.out.println("key: "+key + "值为:"+hashMap.get(key)); 17 } 18 19 System.out.println("treeMap結果"); 20 Map<String, Integer> treeMap = new TreeMap(); 21 treeMap.put("1", 1); 22 treeMap.put("3", 3); 23 treeMap.put("7", 2); 24 treeMap.put("2", 7); 25 treeMap.put("4", 4); 26 Iterator iterator1 =treeMap.keySet().iterator(); 27 while (iterator1.hasNext()) { 28 Object key= iterator1.next(); 29 System.out.println("key: "+key + "值为:"+treeMap.get(key)); 30 } 31 32 System.out.println("LinkedHashMap結果"); 33 Map linkMap= new LinkedHashMap<>(); 34 35 linkMap.put("1", 1); 36 linkMap.put("3", 3); 37 linkMap.put("7", 2); 38 linkMap.put("2", 7); 39 linkMap.put("4", 4); 40 Iterator iterator2 =linkMap.keySet().iterator(); 41 while (iterator2.hasNext()) { 42 Object key= iterator2.next(); 43 System.out.println("key: "+key + "值为:"+linkMap.get(key)); 44 } 45 } 46 47} 48 49----------运行结果:-----------linkMap.put("7", 2); 50linkMap.put("2", 7); //特意将key的值与value的值不一样,看排序是按照key排序还是value的值排序hashmap結果 //随机的,此处看不出来 51key: 1值为:1 52key: 2值为:7 53key: 3值为:3 54key: 4值为:4 55key: 7值为:2 56treeMap結果 //可以看到是按照key值排序的,默认升序 57key: 1值为:1 58key: 2值为:7 59key: 3值为:3 60key: 4值为:4 61key: 7值为:2 62LinkedHashMap結果 //按照插入的顺序排序 63key: 1值为:1 64key: 3值为:3 65key: 7值为:2 66key: 2值为:7 67key: 4值为:4