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确定)
 

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