云中风扬

导航

为什么阿里规范要求 Hash Map 在使用的时候要规定设置好默认值 initial Capacity :

  在当我们对 HashMap 初始化时没有设置初始容量,系统会默认创建一个容量为16大小的集合。当 HashMap 的容量值超过临界值(默认 165.75 = 12 )时,HashMap 将会重新扩容到下一个2的指数幂(16->32)。

  HashMap 扩容将要进行 Resize 的操作,频繁的 Resize 会导致降低性能。所以说不指定大小的话,数据量超过阈值会频繁的触发 resize,耗费资源耗费时间。

public static void main(String[] args) {
        Map<Integer, Integer> map = new HashMap<>(100000);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            map.put(i, i);
        }
        System.out.println("指定大小10000耗时为:" + (System.currentTimeMillis() - start));
 
        Map<Integer, Integer> map02 = new HashMap<>();
        long start2 = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            map02.put(i, i);
        }
        System.out.println("不指定大小耗时为:" + (System.currentTimeMillis() - start2));
    }

  

  HashMap 是线程不安全的,他的不安全就体现在Resize的时候,多线程的情况下,可能会形成环形链表,导致下一次读取的时候可能会出现死循环!!!

  面试经常会问的:

  1.HashMap什么时候扩容呢?
  2.扩容到多少?
  3.怎么扩容呢?
参考答案:
  1.添加元素的时候会检查容器当前元素个数。当HashMap的容量值超过了临界值(默认160.75=12)时扩容。

  2.HashMap将会重新扩容到下一个2的指数幂(16->32)。

  3.调用resize方法,定义长度为新长度(32)的数组,然后对原数组数据进行再Hash。这个过程是一个性能损耗点

posted on 2022-04-12 15:10  Lucky洋同学  阅读(230)  评论(0)    收藏  举报