tableSizeFor(int cap)该方法用来返回大于等于该给定整数的最小2^次幂值;
用到的地方
public HashMap(int initialCapacity, float loadFactor);
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict);
private void readObject(java.io.ObjectInputStream s);
tableSizeFor()方法
static final int MAXIMUM_CAPACITY = 1 << 30;
static final int tableSizeFor(int cap) {
int n = cap - 1;
//相当于 n = n | n >>> 1
//n >>> 1 右移一位
n |= n >>> 1;
System.out.println("n >>> 1 = " + n);
n |= n >>> 2;
System.out.println("n >>> 2 = " + n);
n |= n >>> 4;
System.out.println("n >>> 4 = " + n);
n |= n >>> 8;
System.out.println("n >>> 8 = " + n);
n |= n >>> 16;
System.out.println("n >>> 16 = " + n);
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
Test测试类
public class MapTest {
public static final int MAXIMUM_CAPACITY = 1 << 30;
public static void main(String[] args) {
System.out.println(tableSizeFor(10));//16
}
static final int tableSizeFor(int cap) {
int n = cap - 1;
//相当于 n = n | n >>> 1
n |= n >>> 1;
System.out.println("n >>> 1 = " + n);//13
n |= n >>> 2;
System.out.println("n >>> 2 = " + n);//15
n |= n >>> 4;
System.out.println("n >>> 4 = " + n);//15
n |= n >>> 8;
System.out.println("n >>> 8 = " + n);//15
n |= n >>> 16;
System.out.println("n >>> 16 = " + n);//15
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
}