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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With