Java Tricks —— 不小于一个数的最小2的幂次方

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lanchunhui/article/details/82468705

不小于一个数的最小2的幂次方,对于 10 就是 16,对于 21 就是 32.

以下实现摘自 java HashMap 的源码:

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减1,是为了避免参数cap本来就是2的幂次方,这样一来,经过后续的未操作的,cap将会变成2 * cap,是不符合我们预期的。
  • n >>> 1 使得 n 的最高位为0;
    • n |= n>>>1,则 n 的前两位为1;
  • n |= n >>> 2:n 的前 4 位均为 1;
  • n |= n >>> 4:n 的前 8 为均为 1;
  • n |= n >>> 8:n 的前 16 为均为 1;
  • n |= n >>> 16:n 的前 32 为均为 1;

如果入参为 20:

int n = cap - 1;        // 19, 10011
n |= n >>> 1;           // 21, 11011
n |= n >>> 2;           // 31, 11111
n |= n >>> 4;           // 31, 11111
n |= n >>> 8;           // 31, 11111
n |= n >>> 16;          // 31, 11111
n+1             // 32 = 2^5

源码分析之 HashMap

猜你喜欢

转载自blog.csdn.net/lanchunhui/article/details/82468705