Can you please explain this code snippet from HashMap constructor specifically the line
capacity <<= 1:
// Find a power of 2 >= initialCapacity
198 int capacity = 1;
199 while (capacity < initialCapacity)
200 capacity <<= 1;
It is equivalent to
capacity = capacity << 1;.That operation shifts capacity’s bits one position to the left, which is equivalent to multiplying by 2.
The specific code you posted finds the smallest power of 2 which is larger than
initialCapacity.So if
initialCapacityis 27, for example,capacitywill be 32 (2^5) after the loop.