• HashMap和LinkedMap的区别


    package com.exam;
    
    import java.util.HashMap;
    import java.util.LinkedHashMap;
    import java.util.Map;
    
    /**
     * @author zt on 2020/7/18
     */
    public class Demo3 {
        public static void main(String[] args) {
            Map map = new HashMap();
            map.put("chinese", 110);
            map.put("math", 110);
            map.put("english", 110);
            map.put("phy", 110);
            System.out.println(map); //{phy=110, chinese=110, english=110, math=110}
    
            LinkedHashMap<Object, Object> linkedHashMap = new LinkedHashMap<>();
            linkedHashMap.put("chinese", 110);
            linkedHashMap.put("math", 110);
            linkedHashMap.put("english", 110);
            linkedHashMap.put("phy", 110);
    
            System.out.println(linkedHashMap); //{chinese=110, math=110, english=110, phy=110}
        }
    }

    可见,linkedHashMap是顺序存储;HashMap的存储位置=key的hashCode%初始容量

    package com.exam;
    
    import java.util.HashMap;
    import java.util.LinkedHashMap;
    import java.util.Map;
    
    /**
     * @author zt on 2020/7/18
     */
    public class Demo4 {
        public static void main(String[] args) {
            long count = 1000000;
            Map map1 = new HashMap();
            Map map2 = new LinkedHashMap();
    
            for (int i = 0; i < count; i++) {
                map1.put(i, i);
            }
            for (int i = 0; i < count; i++) {
                map2.put(i, i);
            }
    
            Long startTime, endTime;
            startTime = System.currentTimeMillis();
            for (Object v : map1.values()) {}
            endTime = System.currentTimeMillis();
    
            Long time1 = endTime - startTime;
            System.out.println("HashMap遍历花费的时间:" + time1);
    
            startTime = System.currentTimeMillis();
            for (Object v : map2.values()) {}
            endTime = System.currentTimeMillis();
    
            Long time2 = endTime - startTime;
            System.out.println("LinkedHashMap遍历花费的时间:" + time2);
    
        }
    }

    经过多次运行,当超过500万条数据时,LinkedHashMap的存储速度明显优于HashMap。当数据量为100万条时,LinkedHashMap的遍历速度优于HashMap;但当数据量达到500万条时,HashMap遍历速度明显优于LinkedHashMap。因此要根据实际需求选择使用哪种方式。小数据量的情况下,推荐使用LinkedHashMap。

  • 相关阅读:
    身份证号码的秘密
    SQL Server中的DATEPART函数的使用
    VS2010+Visual Assist X
    Log4Net使用指南
    JScript中的prototype(原型)属性研究
    使用Transaction访问数据库(C#,TransactionScope,.NET 2.0)
    C# 中奇妙的函数–7. String Split 和 Join
    LinqToSQL实例参见
    得到当前网址的域名 ASP.NET
    oracle中delete、truncate、drop的区别
  • 原文地址:https://www.cnblogs.com/tzzt01/p/13338189.html
Copyright © 2020-2023  润新知