关于位运算和HashMap中一个求最小2次幂的算法
今天在HashMap的内部源码的时候,看到这样一个算法:
/**
* Returns a power of two size for the given target capacity.
* 返回大于或等于 cap 的最小2次幂
*/
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}