HashMap原始碼中一個演算法tableSizeFor
阿新 • • 發佈:2019-01-05
閱讀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倍;