HashMap、LinkedHashMap、TreeMap 区别

HashMap,LinkedHashMap,TreeMap都属于Map
Map 主要用于存储键(key)值(value)对,根据键得到值,因此键不允许键重复,但允许值重复。
HashMap 是一个最常用的Map,它根据键的HashCode 值存储数据,根据键可以直接获取它的值,具有很快的访问速度。 HashMap最多只允许一条记录的键为Null;允许多条记录的值为Null; HashMap不支持线程的同步,即任一时刻可以有多个线程同时写 HashMap;可能会导致数据的不一致。如果需要同步,可以用Collections的synchronizedMap方法使 HashMap具有同步的能力。

LinkedHashMap LinkedHashMap也是一个 HashMap,但是内部维持了一个双向链表,可以保持顺序

TreeMap 不仅可以保持顺序,而且可以用于排序

HashMap例子:  
    public static void main(String[] args) {
         //遍历:后放先出
        Map<String, String> map = new HashMap<String, String>();
        map.put("a3", "aa");
        map.put("a2", "bb");
        map.put("b1", "cc");
        for (Iterator iterator = map.values().iterator(); iterator.hasNext();) {
            String name = (String) iterator.next();
            System.out.println(name);
        }
    }

LinkedHashMap例子:

    public static void main(String[] args) {
        //遍历:怎么样放怎么样出
        Map<String, String> map = new LinkedHashMap<String, String>();
        map.put("a3", "aa");
        map.put("a2", "bb");
        map.put("b1", "cc");
        for (Iterator iterator = map.values().iterator(); iterator.hasNext();) {
            String name = (String) iterator.next();
            System.out.println(name);
        }
    }

TreeMap例子:

    public static void main(String[] args) {
        //遍历:不管怎么样放,出的时候都是按key的排序(升序)出。
        Map<String, String> map = new TreeMap<String, String>(new Comparator<Object>(){
            Collator collator = Collator.getInstance(); 
            public int compare(Object o1, Object o2) {
                CollationKey key1 = collator.getCollationKey(o1.toString());
                CollationKey key2 = collator.getCollationKey(o2.toString());
                return key1.compareTo(key2);
                //return collator.compare(o1, o2);
            }});
        map.put("a3", "aa");
        map.put("a2", "bb");
        map.put("b1", "cc");
        for (Iterator iterator = map.values().iterator(); iterator.hasNext();) {
            String name = (String) iterator.next();
            System.out.println(name);
        }
    }

运行这三个例子,体会一下它们之间的区别

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值