简体   繁体   中英

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 ?

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.

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 hashcode s 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM