HashMap的最大容量为什么是1左移30(2的30次方)

/**
 * The maximum capacity, used if a higher value is implicitly specified
 * by either of the constructors with arguments.
 * MUST be a power of two <= 1<<30.
 */
static final int MAXIMUM_CAPACITY = 1 << 30;

<< 这个操作符必须要理解,在一般情况下 1 << x 等于 2^x。这是左移操作符,对二进制进行左移。
来看1 << 30。它代表将1左移30位,也就是0010...0

来看这样一段代码:

public static void main(String[] args){
    for (int i = 30; i <= 33; i++) {
        System.out.println("1 << "+ i +" = "+(1 << i));
    }
    System.out.println("1 << -1 = " + (1 << -1));

}

输出结果为:

1 << 30 = 1073741824
1 << 31 = -2147483648
1 << 32 = 1
1 << 33 = 2
1 << -1 = -2147483648

首先:JAVA规定了该static final 类型的静态变量为int类型,至于为什么不是byte、long等类型,原因是由于考虑到HashMap的性能问题而作的折中处理!

由于int类型限制了该变量的长度为4个字节共32个二进制位,按理说可以向左移动31位即2的31次幂。但是事实上由于二进制数字中最高的一位也就是最左边的一位是符号位,用来表示正负之分(0为正,1为负)。如果把1(000…001)向左移动31位,最高位就是1(100…000)了,此时就变成一个负数,所以1<<31=-2147483648。,所以只能向左移动30位,而不能移动到处在最高位的符号位!

发布了272 篇原创文章 · 获赞 19 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/hello_cmy/article/details/105114725