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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章