Map集合接口概述

Map接口定义了以key,value形式存数据,通过key映射将某个value存储到某个地址下的方式来实现。

Map下实现的接口有hashMap,hashTable,LinkedHashMap,TreeMap等一系列的实现类

一个丑丑的uml图献上

1.HashMap

我们最常用的Map实现,底层采用数组+单链表+红黑树实现的,存的数据取出来是无序的(所以对应就会出现有序的实现LinkedHashMap)!但是hashMap的查找效率是很高的哦!

     public static void main(String[] args) {   
        Map<String,String> map = new HashMap(16);
        map.put("2", "xxh");
        map.put("1", "df");
        map.put("6", "er");
        map.put("68", "er");
        map.put("80", "er");
        for (Iterator it = map.keySet().iterator(); it.hasNext(); ) {
            Object key = it.next();
            System.out.println(key + "=" + map.get(key));
        }
     }

2.TreeMap

底层红黑树实现的,存的数据取出来是无序的,因为会根据它的key自然顺序进行排序,或者根据创建映射时提供的 Comparator 进行排序。

  public static void main(String[] args) {
        Map<String,String> map = new TreeMap();
        map.put("2", "xxh");
        map.put("1", "df");
        map.put("6", "er");
        map.put("68", "er");
        map.put("80", "er");
        for (Iterator it = map.keySet().iterator(); it.hasNext(); ) {
            Object key = it.next();
            System.out.println(key + "=" + map.get(key));
        }
    }
看吧,按照key自动的排为了升序。

  自定义排序实现倒叙试试

 public static void main(String[] args) {
        Comparator<Integer> comparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2-o1;
            }
        };
        Map<Integer, Integer> map = new TreeMap(comparator);
        map.put(2, 3);
        map.put(1, 5);
        map.put(6, 2);
        map.put(68, 6);
        map.put(80, 9);
        for (Iterator it = map.keySet().iterator(); it.hasNext(); ) {
            Object key = it.next();
            System.out.println(key + "=" + map.get(key));
        }
    }

   

如果不需要排序的话尽量使用HashMap,因为TreeMap采用的红黑树,插入,删除也好需要维持平衡,查询的话因为HashMap是采用映射查询,TreeMap是树所以会依次遍历查找,所以性能还是HashMap好

3.LinkedHashMap

LinkedHashMap底层采用的是链表实现,插入数据与存储数据是顺序是一致的。

 public static void main(String[] args) {
        Map<Integer, Integer> map = new LinkedHashMap();
        map.put(2, 3);
        map.put(1, 5);
        map.put(6, 2);
        map.put(68, 6);
        map.put(80, 9);
        for (Iterator it = map.keySet().iterator(); it.hasNext(); ) {
            Object key = it.next();
            System.out.println(key + "=" + map.get(key));
        }
    }

4.HashTable

线程安全的HashMap,直接把synchronized加入到方法里了,所以性能不高,一般不建议使用HashTable,线程安全建议使用ConcurrentHashMap,ConcurrentHashMap采用CAS+synchronized方式实现的,所以性能会很高

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值