Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does & bit operator work here?

In Java Collection classes, I have noticed very often codes like below

  //ArrayDeque
    public E pollFirst() {
    int h = head;
    @SuppressWarnings("unchecked")
    E result = (E) elements[h];
    // Element is null if deque empty
    if (result == null)
        return null;
    elements[h] = null;     // Must null out slot
    head = (h + 1) & (elements.length - 1);
    return result;
}

What does head = (h + 1) & (elements.length - 1); do ? Why is & operator used here and what purpose does it serve.

My Question is not how & works, but what's its use here.

Can anyone explain it ?

like image 704
Roshan Avatar asked Jul 08 '17 09:07

Roshan


2 Answers

It is a shortcut for (h + 1) % elements.length that only works if elements.length is a power of two. On some older hardware this may have run slightly faster, although I doubt this is still the case on a modern CPU.

like image 112
Henry Avatar answered Oct 09 '22 03:10

Henry


That & operation is not a true equivalent for %, think negative numbers. It's not the case here, but there are other places where this matters (like HashMap), where this is done via :

(n - 1) & hash // n - current capacity, hash - hashcode

Since hashcodes are int values - they can be negative numbers. Using % instead of & would result in a negative number, which simply can't happen for HashMap (since that is the bucket number).

like image 1
Eugene Avatar answered Oct 09 '22 02:10

Eugene