new HashMap()和Maps.newHashMap()的区别以及 newHashMapWithExpectedSize()

  1、new HashMap() 这种是java原生API写法,需要你手动加泛型。存在线程安全问题,在扩容计算hash的时候会出现安全问题,在rehash方法中,有兴趣的可以去看一下源码


Map<String, Object> result = new HashMap<String,Object>();

         

  2、Maps.newHashMap(),这种是google的guava.jar提供的写法,目的是为了简化代码,不需要你手动写泛型。挺方便的,代码看着也挺整洁的,也存在安全问题,因为它本质上也是给你返回的一个HashMap(),所以安全方面和HashMap一样


Map<String, Object> result = Maps.newHashMap();

     newHashMap()源码:

/**
   * Creates a <i>mutable</i>, empty {@code HashMap} instance.
   *
   * <p><b>Note:</b> if mutability is not required, use {@link
   * ImmutableMap#of()} instead.
   *
   * <p><b>Note:</b> if {@code K} is an {@code enum} type, use {@link
   * #newEnumMap} instead.
   *
   * @return a new, empty {@code HashMap}
   */
  public static <K, V> HashMap<K, V> newHashMap() {
    return new HashMap<K, V>();
  }

3、 Maps.newHashMapWithExpectedSize(10) 这个创建实例时需要设置默认元素个数,

源码分析:

        我们通过 expectedSize + expectedSize / 3  计算 10+10/3 = 13,经过计算就会被设置为13,也就是多扩了1/3,

        当HashMap内部维护的哈希表的容量达到75%时(默认情况下),会触发rehash,而rehash的过程是比较耗费时间的。所以初始化容量要设置成expectedSize + expectedSize / 3的话,可以有效的减少冲突也可以减小误差。

       所以,我可以认为,当我们明确知道HashMap中元素的个数的时候,把默认容量设置成expectedSize + expectedSize / 3 是一个在性能上相对好的选择,但是,同时也会牺牲些内存。

 public static <K, V> HashMap<K, V> newHashMapWithExpectedSize(
      int expectedSize) {
    return new HashMap<K, V>(capacity(expectedSize));
  }


/**
   * Returns a capacity that is sufficient to keep the map from being resized as
   * long as it grows no larger than expectedSize and the load factor is >= its
   * default (0.75).
   */
  static int capacity(int expectedSize) {
    if (expectedSize < 3) {
      checkNonnegative(expectedSize, "expectedSize");
      return expectedSize + 1;
    }
    if (expectedSize < Ints.MAX_POWER_OF_TWO) {
      return expectedSize + expectedSize / 3;
    }
    return Integer.MAX_VALUE; // any large value
  }

4、上面这三个Map都不是线程安全的,因为他们本质就是HashMap,原因 1 那个也说了,如果需要线程安全的话就使用ConcurrentMap,这个是线程安全的 ,它里面有个标志位必须是当前线程拿到这个标志位才可以进行 进行 rehash 操作,简单来说就是里面有个锁控制,这个就要牵扯到线程方面的问题了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值