最近在看Java8 HashMap的源码的时候,发现有参构造方法会调用tableSizeFor方法来确认容量的大小,tableSizeFor方法里面的算法挺巧妙的,所以专门研究了下,下面跟大家分享下我对tableSizeFor方法的一个理解。
我们先看看方法源码:
/**
* 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;