What does this boolean “(number & 1) == 0” mean?

前端 未结 9 909
眼角桃花
眼角桃花 2020-12-08 01:27

On CodeReview I posted a working piece of code and asked for tips to improve it. One I got was to use a boolean method to check if an ArrayList had an even number of indices

9条回答
  •  萌比男神i
    2020-12-08 02:01

    The & operator in Java is the bitwise-and operator. Basically, (number & 1) performs a bitwise-and between number and 1. The result is either 0 or 1, depending on whether it's even or odd. Then the result is compared with 0 to determine if it's even.

    Here's a page describing bitwise operations.

提交回复
热议问题