阅读JDK1.8版本HashMap源码看到的一段代码,返回大于等于指定入参的最小2的幂。
1 /** 2 * The maximum capacity, used if a higher value is implicitly specified 3 * by either of the constructors with arguments. 4 * MUST be a power of two <= 1<<30. 5 */ 6 static final int MAXIMUM_CAPACITY = 1 << 30; 7 8 /** 9 * Returns a power of two size for the given target capacity. 10 */ 11 static final int tableSizeFor(int cap) { 12 int n = cap - 1; 13 n |= n >>> 1; 14 n |= n >>> 2; 15 n |= n >>> 4; 16 n |= n >>> 8; 17 n |= n >>> 16; 18 return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; 19 }
int n = cap-1;防止入参本身为2的幂,若不进行减一操作,结果将得到本身的2倍;
原文地址:https://www.cnblogs.com/caster-xzn/p/10225330.html
时间: 2024-11-08 02:04:00