1 /* 2 * Copyright (C) 2014 Google, Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package dagger.internal; 17 18 import java.util.LinkedHashMap; 19 import java.util.LinkedHashSet; 20 21 final class Collections { 22 /** 23 * The maximum value for a signed 32-bit integer that is equal to a power of 2. 24 */ 25 private static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2); 26 27 private Collections() { 28 } 29 30 /** 31 * Creates a {@link LinkedHashSet} instance, with a high enough "initial capacity" that it 32 * <em>should</em> hold {@code expectedSize} elements without growth. 33 */ 34 static <E> LinkedHashSet<E> newLinkedHashSetWithExpectedSize(int expectedSize) { 35 return new LinkedHashSet<E>(calculateInitialCapacity(expectedSize)); 36 } 37 38 /** 39 * Creates a {@link LinkedHashMap} instance, with a high enough "initial capacity" that it 40 * <em>should</em> hold {@code expectedSize} elements without growth. 41 */ 42 static <K, V> LinkedHashMap<K, V> newLinkedHashMapWithExpectedSize(int expectedSize) { 43 return new LinkedHashMap<K, V>(calculateInitialCapacity(expectedSize)); 44 } 45 46 private static int calculateInitialCapacity(int expectedSize) { 47 if (expectedSize < 3) { 48 return expectedSize + 1; 49 } 50 if (expectedSize < MAX_POWER_OF_TWO) { 51 // This is the calculation used in JDK8 to resize when a putAll 52 // happens; it seems to be the most conservative calculation we 53 // can make. 0.75 is the default load factor. 54 return (int) (expectedSize / 0.75F + 1.0F); 55 } 56 return Integer.MAX_VALUE; // any large value 57 } 58 } 59