zoukankan      html  css  js  c++  java
  • 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。

  • 相关阅读:
    使用JDBC连接并操作数据库
    JDBC连接数据库的url设useSSL参数为true产生的问题
    0-1背包问题的学习及LeetCode相关习题练习
    MySQL---操作数据库
    6、Python Requests库高级操作【2】
    5、Python Requests库高级操作【1】
    4、Python 数据解析【2】
    3、Python 数据解析【1】
    Python正则re.S,re.I等作用
    2、Python 使用Requests库通用爬取数据操作
  • 原文地址:https://www.cnblogs.com/tzzt01/p/13338189.html
Copyright © 2011-2022 走看看