hashMap put方法 第三行代码
inflateTable(threshold)
分析:
Hi.java
public class Hi { //临界值(一个值最接近2的n次幂的数,比如7的临界值为8) int threshold; //2的30次方,01000000 00000000 00000000 00000000(最大) static final int MAXIMUM_CAPACITY = 1 << 30; //初始容量为 16(缺省) static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 //加载因子默认为 0.75 static final float DEFAULT_LOAD_FACTOR = 0.75f; //加载因子 final float loadFactor; //构造函数,初始化时传入了两个值:初始容量和默认加载因子 public Hi() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); } //构造函数,接收初始容量和加载因子 public Hi(int initialCapacity, float loadFactor) { //如果初始容量小于0,则抛出异常 if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); //如果初始容量大于最大容量,则初始容量还是要等于最大限量 if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; //如果加载因子小于0或为空,则抛出异常 if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); //赋值类的加载因子属性为传入的加载因子,不传默认为0.75 this.loadFactor = loadFactor; //为临界值赋值,赋值为初始容量16 threshold = initialCapacity; init(); } void init() { } //提供一个对外的方法,返回值为临界值,用来验证 public int getSize(){ //当调用getSize方法时,threshold因为被构造函数赋值,所以此时为16 System.out.println(threshold); //把threshold传入roundUpToPowerOf2,计算临界值 int size = roundUpToPowerOf2(threshold); return size; } //计算出大于toSize最临近的2的N此方的值 private static int roundUpToPowerOf2(int number) { //稍后分析 return number >= MAXIMUM_CAPACITY ? MAXIMUM_CAPACITY : (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1; } }
Hs.java
public class Hs { public static void main(String []args) { Hi hi = new Hi(); int a = hi.getSize(); System.out.println(a); } }
此时结果为:
F:\java>java Hs
16
16