一般Java的集合初始化如下带初始容量的map:
Map map = new HashMap(4);
本意是希望给HashMap设置初始值, 避免扩容(resize)的开销. 但是没有考虑当添加的元素数量达到HashMap容量的75%时将出现resize.
所以说上面的是徒劳的。错误的。
guava里面有工具类Maps,可以很方便的创建一个集合,并且,带上合适的大小初始化值。具体如下:
Map<String, Object> map = Maps.newHashMapWithExpectedSize(7);
二者的详细对比如下:
-
-
- Map<String, Object> map = Maps.newHashMapWithExpectedSize(7);
-
-
- public static <K, V> HashMap<K, V> newHashMapWithExpectedSize(int expectedSize) {
- return new HashMap<K, V>(capacity(expectedSize));
- }
-
- static int capacity(int expectedSize) {
- if (expectedSize < 3) {
- checkNonnegative(expectedSize, "expectedSize");
- return expectedSize + 1;
- }
- if (expectedSize < Ints.MAX_POWER_OF_TWO) {
-
-
-
- return (int) ((float) expectedSize / 0.75F + 1.0F);
- }
- return Integer.MAX_VALUE;
- }
-
- public HashMap(int initialCapacity) {
- this(initialCapacity, DEFAULT_LOAD_FACTOR);
- }
-
-
- int capacity = 1;
- while (capacity < initialCapacity)
- capacity <<= 1;
-
- threshold = (int) (capacity * loadFactor);
-
-
- if (size++ >= threshold)
- resize(2 * table.length);
-
-
- this.threshold = tableSizeFor(initialCapacity);
-
- static final int tableSizeFor(int cap) {
- int n = cap - 1;
- n |= n >>> 1;
- n |= n >>> 2;
- n |= n >>> 4;
- n |= n >>> 8;
- n |= n >>> 16;
- return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
- }
-
-
- if (++size > threshold)
- resize();
-
-