SortedMap接口实现排序

SortedMap接口主要提供有序的Map实现。SortedMap接口是排序接口,只要是实现了此接口的子类,都属于排序的子类,TreeMap也是此接口的一个子类

Map的主要实现有HashMap,TreeMap,HashTable,LinkedHashMap。

TreeMap实现了SortedMap接口,保证了有序性。默认的排序是根据key值进行升序排序,也可以重写comparator方法来根据value进行排序。

HashMap与TreeMap的比较

 Map<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("1", "a");
        hashMap.put("5", "b");
        hashMap.put("2", "c");
        hashMap.put("4", "d");
        hashMap.put("3", "e");
        Set<Map.Entry<String, Object>> entry = hashMap.entrySet();
        for (Map.Entry<String, Object> temp : entry) {
            System.out.println("hashMap:" + temp.getKey() + " 值" + temp.getValue());
        }

        System.out.println("\n");

        SortedMap<String, Object> sortedMap = new TreeMap<String, Object>();
        sortedMap.put("1", "a");
        sortedMap.put("5", "b");
        sortedMap.put("2", "c");
        sortedMap.put("4", "d");
        sortedMap.put("3", "e");
        Set<Map.Entry<String, Object>> entry2 = sortedMap.entrySet();
        for (Map.Entry<String, Object> temp : entry2) {
            System.out.println("sortedMap:" + temp.getKey() + " 值" + temp.getValue());
        }

看上去还以为HashMap也保证了有序性,其实是随机的,如果值设置的复杂一点,如下例

 

 Map<String,Object> hashMap = new HashMap<String,Object>();
        hashMap.put("1b", "a");
        hashMap.put("2", "b");
        hashMap.put("4b", "d");
        hashMap.put("3", "c");
        hashMap.put("2b", "d");
        hashMap.put("3b", "c");
        Set<Map.Entry<String, Object>> entry = hashMap.entrySet();
        for(Map.Entry<String, Object> temp : entry){
            System.out.println("hashMap:"+temp.getKey()+" 值"+temp.getValue());
        }

        System.out.println("\n");

        SortedMap<String,Object> sortedMap = new TreeMap<String,Object>();
        sortedMap.put("1b", "a");
        sortedMap.put("2", "b");
        sortedMap.put("4b", "d");
        sortedMap.put("3", "c");
        sortedMap.put("2b", "d");
        sortedMap.put("3b", "c");
        Set<Map.Entry<String, Object>> entry2 = sortedMap.entrySet();
        for(Map.Entry<String, Object> temp : entry2){
            System.out.println("sortedMap:"+

很显然只有TreeMap保证了有序性。

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值