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

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);
			  }
		  }};
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值