Java集合详解三:HashMap、LinkedHashMap、TreeMap、Hashtable的区别与使用

  我们在Java中经常使用的即为HashMap,基于哈希表进行实现,其内部是无序的,非线程安全,所以速度较快。

  LinkedHashMap基于 哈希表+链表进行实现,其顺序是put的顺序来排序,即先入排在最前面,非线程安全
  TreeMap基于 红黑树进行实现,其内部是有序的,排序规则是安全其中key实现的compareable接口来进行排序,非线程安全
  Hashtable与HashMap类似,基于 哈希表进行实现,方法加入 synchronized,内部无序,线程安全,速度较慢


一、HashMap:
        People people1 = new People(18, "name1");
        People people2 = new People(25, "name2");
        People people3 = new People(16, "name3");


        // hashMap
        HashMap<People, String> hashMap = new HashMap<>();
        hashMap.put(people1, "a");
        hashMap.put(people2, "b");
        hashMap.put(people3, "c");


        Iterator<Map.Entry<People, String>> hashMapIterator = hashMap.entrySet().iterator();
        while (hashMapIterator.hasNext()){
            People people = hashMapIterator.next().getKey();
            System.out.println("年龄为" + people.getAge());
        }
结果为:
年龄为25
年龄为18
年龄为16

可以看到是无序的。


二、LikedHashMap:
        LinkedHashMap<People, String> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put(people1, "a");
        linkedHashMap.put(people2, "b");
        linkedHashMap.put(people3, "c");


        Iterator<Map.Entry<People, String>> linkedHashMapIterator = linkedHashMap.entrySet().iterator();
        while (linkedHashMapIterator.hasNext()){
            People people = linkedHashMapIterator.next().getKey();
            System.out.println("年龄为" + people.getAge());
        }

年龄为18
年龄为25
年龄为16


三、TreeMap:
        TreeMap<People, String> treeMap = new TreeMap<>();
        treeMap.put(people1, "a");
        treeMap.put(people2, "b");
        treeMap.put(people3, "c");


        Iterator<Map.Entry<People,String>> iterator = treeMap.entrySet().iterator();
        while (iterator.hasNext()) {
            People people = iterator.next().getKey();
            System.out.println("年龄为" + people.getAge());
        }
结果为:


年龄为16
年龄为18
年龄为25

可以看到,按照People的Comparable来进行排序


四、Hashtable:
        Hashtable<People, String> hashtable = new Hashtable<>();
        hashtable.put(people1, "a");
        hashtable.put(people2, "b");
        hashtable.put(people3, "c");

        Iterator<Map.Entry<People, String>> hashTableIterator = hashtable.entrySet().iterator();
        while (hashTableIterator.hasNext()){
            People people = hashTableIterator.next().getKey();
            System.out.println("年龄为" + people.getAge());
        }


返回值为:
年龄为16
年龄为25
年龄为18

可见也是无序的。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值