HashMap初始化指定大小,负载因子0.75

mac2024-03-24  30

import java.util.HashMap; import java.util.Map; public class HashMapUtil { /** * The largest power of two that can be represented as an {@code int}. * * @since 10.0 * 00000000 00000000 00000000 00000001 = 1 * 01000000 00000000 00000000 00000000 = 1073741824(10亿多) * Integer.MAX_VALUE = 2147483647(21亿多) */ private static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2);//(10亿多) /** * 来源google-guava * @author:heshengjin qq:2356899074 @date 2019年10月31日 上午10:21:37 */ public static int capacity(int expectedSize) { if (expectedSize < 3) { return expectedSize + 1; } if (expectedSize < MAX_POWER_OF_TWO) { // This is the calculation used in JDK8 to resize when a putAll // happens; it seems to be the most conservative calculation we // can make. 0.75 is the default load factor. return (int) ((float) expectedSize / 0.75F + 1.0F); } return Integer.MAX_VALUE; // any large value } @SuppressWarnings({ "serial", "unused" }) public static void main(String[] args) { //创建的时候初始化值 Map<String, Integer> map = new HashMap<String, Integer>(capacity(100)){{ for(int i = 0,ilen = 100;i <= ilen; i++){ put("HashMapTest_"+i, i); } }}; } }
最新回复(0)