hashmap 的数量是保证容量为2的整数幂 那么他是如何保证的呢:
通过一下方法确认的,比方我们输入13,其实最终是16也就是输出最近的2的整数幂
/**
* Returns a power of two size for the given target capacity.
*/
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;
}
下面详细分析下:
加入cap为7,也就是0000 0000 0000 0111,
首先向右位移1位 0000 0000 0000 0011,异或:0000 0000 0000 0100,
再向右位移2位 0000 0000 0000 0001 异或 0000 0000 0000 0101
向右位移4位,
向右移动8位,为