通过tableSizeFor(cap)计算出不小于initialCapacity的最近的2的幂作为初始容量,将其先保存在threshold里
/**
* @description HashMap扩容测试
* << : 左移运算符,num << 1,相当于num乘以2
* >> : 右移运算符,num >> 1,相当于num除以2
* >>> : 无符号右移,忽略符号位,空位都以0补齐
*/
public class HashMapCapacityTest {
private static final int MAXIMUM_CAPACITY = 1 << 30;
//0b01000000_00000000_00000000_00000000
public static void main(String[] args) {
int n = 9;
/**
* n |= n >>> 1;
* n |= n >>> 2;
* n |= n >>> 4;
* n |= n >>> 8;
* n |= n >>> 16
**/
n = n | n >>> 1;//1001|0100 ---->1101(13)
System.out.println("n =n| n >>> 1 : " + n);
n = n | n >>> 2;//1101|0011 ---->1111(15)
System.out.println("n =n| n >>> 2 : " + n);
n = n | n >>> 4;//1111|0111 ---->1111(15)
System.out.println("n =n| n >>> 4 : " + n);
n = n | n >>> 8;//1111|0111 ---->1111(15)
System.out.println("n =n| n >>> 8 : " + n);
n = n | n >>> 16;//1111|0111 ---->1111(15)
System.out.println("n =n| n >>> 16 : " + n);
n = (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
System.out.println(n);
}
}
打印结果:
n =n| n >>> 1 : 13
n =n| n >>> 2 : 15
n =n| n >>> 4 : 15
n =n| n >>> 8 : 15
n =n| n >>> 16 : 15
16
PS:
idea 可以通过此方法转为二进制模式