HashMap the constructor of the specified initial capacity:
The initial capacity is based on the parameter initialcapacity, to find the smallest of more than equal to Initialcapacity 2 N-th square.
The capacity is 2 of the n-th side reason, see http://www.cnblogs.com/xwdreamer/archive/2012/06/03/2532832.html
1, in the lower JDK version, through the cyclic shift operation, to ensure that the initial capacity of 2 of the N-square
Public HashMap (int initialcapacity, float loadfactor) { ... int capacity = 1; while (capacity < initialcapacity) capacity <<= 1; ...... }
2. In JDK1.8, the operation is optimized
Public HashMap (int initialcapacity, float loadfactor) { ... This.threshold = Tablesizefor (initialcapacity);} static final int tablesizefor (int cap) { int n = cap-1; n |= n >>> 1; N |= n >>> 2; N |= n >>> 4; N |= n >>> 8; n |= n >>>; Return (n < 0)? 1: (n >= maximum_capacity)? Maximum_capacity:n + 1;}
The 2.1 parameter is not a 2 N-square, and is converted to binary
1XXXXXXXX (assuming 9 bits, X has at least one of 1), greater than or equal to the number of the minimum 2 of the n-th square as follows, 10-bit
1000000000
The first step 1xxxxxxxx-1, because the low level has at least one 1, so minus 1, the number of digits unchanged
Second step n |= n >>> 1; 1xxxxxxxx right Shift one becomes 1xxxxxxx, or the operation becomes 11xxxxxxx, regardless of the low
Step three n |= n >>> 2; 11xxxxxxx right shift two bit to 11xxxxx, or to 1111xxxxx after operation, regardless of low
Fourth Step n |= n >>> 4; 1111xxxxx right shift four bit to 1111x, or to 11111111x after operation, regardless of low
......
Ultimately, all lows are guaranteed to be 1:1xxxxxxxx 111111111. +1 becomes 1000000000, which is greater than or equal to the minimum 2 of the number of N-Squares
right Shift or operation, up to 16, can guarantee that up to 32 bits are 1, because the maximum value of the int type 2-1 , is 31-bit
The 2.2 parameter is 2 of the n-th square
For example, the n-1 becomes 111, the right shift or the operation is 111, and +1 turns 1000.
3. Comparison
In the lower version, assuming that the parameter is 2 of the N-square, the comparison + displacement, calculated a total of 2 * N times
JDK1.8, subtraction + displacement + or operation, approximately 11 times
That is, the JDK1.8 is more efficient when you specify 6 (64) of the array's capacity greater than 2
4, the transfer parameter is exactly 2 of the N-time optimization
If a number n is not 1, and n-1 & n = 0, then n is an integer power of 2
JDK1.8 Riga This judgment can reduce the calculation
static final int tablesizefor (int cap) { int n = cap-1; if (Cap & n = 0)//2 n return (Cap >= maximum_capacity)? Maximum_capacity:cap; n |= n >>> 1; N |= n >>> 2; N |= n >>> 4; N |= n >>> 8; n |= n >>>; Return (n < 0)? 1: (n >= maximum_capacity)? Maximum_capacity:n + 1;}
HASHMAP Specifies the initial capacity, which is calculated on different versions of the JDK