HashMap,LinkedHashMap,TreeMap的有序性

HashMap 实际上是一个链表的数组。HashMap 的一个功能缺点是它的无序性,被存入到 HashMap 中的元素,在遍历 HashMap 时,其输出是无序的。如果希望元素保持输入的顺序,可以使用 LinkedHashMap 替代。

LinkedHashMap继承自HashMap,具有高效性,同时在HashMap的基础上,又在内部增加了一个链表,用以存放元素的顺序。LinkedHashMap内部多了一个双向循环链表的维护,该链表是有序的,可以按元素插入顺序或元素最近访问顺序(LRU)排列,简单地说:LinkedHashMap=散列表+循环双向链表

LinkedHashMap 是根据元素增加或者访问的先后顺序进行排序,TreeMap 则是基于元素的固有顺序 (由 Comparator 或者 Comparable 确定)。而 TreeMap 则根据元素的 Key 进行排序。

public class TreeMapTest {

    public static void main(String args[]){
        
        Map<String, Integer> hashMap = new HashMap<>();
        System.out.println("hashmap結果");
        
        hashMap.put("1", 1);
        hashMap.put("3", 3);
        hashMap.put("7", 2);
        hashMap.put("2", 7);
        hashMap.put("4", 4);
        Iterator iterator =hashMap.keySet().iterator();
        while (iterator.hasNext()) {
            Object key=  iterator.next();
            System.out.println("key: "+key + "值为:"+hashMap.get(key));
        }
        
        System.out.println("treeMap結果");
        Map<String, Integer> treeMap = new TreeMap();
        treeMap.put("1", 1);
        treeMap.put("3", 3);
        treeMap.put("7", 2);
        treeMap.put("2", 7);
        treeMap.put("4", 4);
        Iterator iterator1 =treeMap.keySet().iterator();
        while (iterator1.hasNext()) {
            Object key=  iterator1.next();
            System.out.println("key: "+key + "值为:"+treeMap.get(key));
        }
        
        System.out.println("LinkedHashMap結果");
        Map  linkMap= new LinkedHashMap<>();
        
        linkMap.put("1", 1);
        linkMap.put("3", 3);
        linkMap.put("7", 2);
        linkMap.put("2", 7);
        linkMap.put("4", 4);
        Iterator iterator2 =linkMap.keySet().iterator();
        while (iterator2.hasNext()) {
            Object key=  iterator2.next();
            System.out.println("key: "+key + "值为:"+linkMap.get(key));
        }
    }
        
}

----------运行结果:-----------linkMap.put("7", 2);
linkMap.put("2", 7);  //特意将key的值与value的值不一样,看排序是按照key排序还是value的值排序hashmap結果  //随机的,此处看不出来
key: 1值为:1
key: 2值为:7
key: 3值为:3
key: 4值为:4
key: 7值为:2
treeMap結果 //可以看到是按照key值排序的,默认升序
key: 1值为:1
key: 2值为:7
key: 3值为:3
key: 4值为:4
key: 7值为:2
LinkedHashMap結果   //按照插入的顺序排序
key: 1值为:1
key: 3值为:3
key: 7值为:2
key: 2值为:7
key: 4值为:4

评论

暂无评论