Reputation: 27193
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;
Upvotes: 5
Views: 331
Reputation: 2513
every time this comes out of the loop the value of 'capacity' goes 2 raised by a power higher.
like initially it is 1 i.e.2^0; the operation(capacity <<= 1) for the first time makes it 2^1 and then 2^2 and so on. May be you would like to see the more on it at http://www.tutorialspoint.com/java/java_basic_operators.htm
Upvotes: 0
Reputation: 328598
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 initialCapacity
is 27, for example, capacity
will be 32 (2^5) after the loop.
Upvotes: 11
Reputation: 12819
Just like var += 1
is about equivalent to var = var + 1
, what you see here (var <<= 1
) is about equivalent to var = var << 1
, which is "set var
to be the result of a 1
-position binary left-shift of var
."
In this very specific case, it's actually a slightly (runtime) faster way of expressing capacity *= 2
(because a bitwise left-shift of 1 position is equivalent to a multiplication by 2).
Upvotes: 4
Reputation: 6221
It is equivalent of
capacity = capacity << 1;
which shifts bits in capacity
one position to the left (so i.e. 00011011
becomes 00110110
).
Upvotes: 3