Map的有序性

//使用LinkedHashMap代替無序的HashMap實現

 public static void main(String[] args) {

        /**
     * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
     * with the default initial capacity (16) and load factor (0.75).
     */
        Map<String,Integer> linkedMap = new LinkedHashMap();
        linkedMap.put("a",14);
        linkedMap.put("c",18);
        linkedMap.put("x",19);

/**
    默認排序,支持comparable排序方式自定義
*/
        Map<String,Integer> treeMap = new TreeMap();
        treeMap.put("a",11);
        treeMap.put("x",10);
        treeMap.put("c",9);
        treeMap.put("b",100);

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
        Map<String,Integer> hashMap = new HashMap<>();
        hashMap.put("a",11);
        hashMap.put("x",10);
        hashMap.put("e",9);
        hashMap.put("b",100);
        for (Map.Entry<String, Integer> entry : linkedMap.entrySet()){
            System.out.println(entry.getKey()+"===="+entry.getValue());
        }
        System.out.println("========我是分割線=======");
        for (Map.Entry<String, Integer> entry : treeMap.entrySet()){
            System.out.println(entry.getKey()+"===="+entry.getValue());
        }
        System.out.println("========我是分割線=======");
        for (Map.Entry<String, Integer> entry : hashMap.entrySet()){
            System.out.println(entry.getKey()+"===="+entry.getValue());
        }
        //System.out.println(result);
    }

 

HashMap ;無序,高效

TreeMap:能夠根據主鍵自動進行排序

LinkedHashMap:先進先出...即按照add的先後順序排序.

 

LinkedHashMap是一個鏈表的數組.基於HashMap的鏈表方式實現機制.具有高效性,同時在內部增加了一個鏈表,用以存放元素的順序.根據元素增加或者訪問的先後順序進行排序.

HashMap的一個功能缺點是他的無序性,被存入到HashMap中的元素,在遍歷HashMap時,其輸出是無序的.

TreeMap提供了一種完全不同的Map實現.TreeMap有着比HashMap更爲強大的功能,實現了SortedMap接口.TreeMap的迭代輸出將會以元素順序進行.TreeMap的排序則根據元素的key進行排序,是基於元素的固有順序(由Comparator或者Comparable確定)
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章