new HashMap()和Maps.newHashMap()的區別是什么,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
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 }
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。