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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值