溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

new HashMap()和Maps.newHashMap()的區(qū)別是什么

發(fā)布時(shí)間:2021-06-21 15:46:10 來源:億速云 閱讀:196 作者:Leah 欄目:大數(shù)據(jù)

new HashMap()和Maps.newHashMap()的區(qū)別是什么,很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。

1、new HashMap() 這種是java原生API寫法,需要你手動(dòng)加泛型。存在線程安全問題,在擴(kuò)容計(jì)算hash的時(shí)候會(huì)出現(xiàn)安全問題,在rehash方法中,有興趣的可以去看一下源碼

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

2、Maps.newHashMap(),這種是google的guava.jar提供的寫法,目的是為了簡(jiǎn)化代碼,不需要你手動(dòng)寫泛型。挺方便的,代碼看著也挺整潔的,也存在安全問題,因?yàn)樗举|(zhì)上也是給你返回的一個(gè)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) 這個(gè)創(chuàng)建實(shí)例時(shí)需要設(shè)置默認(rèn)元素個(gè)數(shù),

        源碼分析:

          我們通過 expectedSize + expectedSize / 3  計(jì)算 10+10/3 = 13,經(jīng)過計(jì)算就會(huì)被設(shè)置為13,也就是多擴(kuò)了1/3,

          當(dāng)HashMap內(nèi)部維護(hù)的哈希表的容量達(dá)到75%時(shí)(默認(rèn)情況下),會(huì)觸發(fā)rehash,而rehash的過程是比較耗費(fèi)時(shí)間的。所以初始化容量要設(shè)置成expectedSize + expectedSize / 3的話,可以有效的減少?zèng)_突也可以減小誤差。

          所以,我可以認(rèn)為,當(dāng)我們明確知道HashMap中元素的個(gè)數(shù)的時(shí)候,把默認(rèn)容量設(shè)置成expectedSize + expectedSize / 3 是一個(gè)在性能上相對(duì)好的選擇,但是,同時(shí)也會(huì)犧牲些內(nèi)存。

     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
      }

    看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。

    向AI問一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI