Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does <<= operator mean in Java?

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;
like image 666
Geek Avatar asked Aug 22 '12 11:08

Geek


People also ask

What does <<= mean in Java?

"<<" means left shift the bits of a value. ">>" means right shift the bits of a value. example: int a = 5; //the binary value of 5 is 101.

What does this operator mean in Java?

What Does Operator Mean? An operator, in Java, is a special symbols performing specific operations on one, two or three operands and then returning a result. The operators are classified and listed according to precedence order. Java operators are generally used to manipulate primitive data types.

What does >> and << mean in Java?

The signed left shift operator << shifts a bit pattern to the left, and the signed right shift operator >> shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand.

What is the use of >>> operator in Java?

The >>> operator is the unsigned right bit-shift operator in Java. It effectively divides the operand by 2 to the power of the right operand, or just 2 here.


1 Answers

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.

like image 79
assylias Avatar answered Sep 21 '22 18:09

assylias