How does & bit operator work here?

Roshan :

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 ?

Henry :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=460545&siteId=1