The following code is from ArrayDeque in the standard java library. I chose it somewhat arbitrarily since there are many examples of this idea throughout the code.
public void addFirst(E e) {
if (e == null)
throw new NullPointerException();
elements[head = (head - 1) & (elements.length - 1)] = e;
if (head == tail)
doubleCapacity();
}
Basically, as I read it, the value of head is reduced by one, and then bitwise "anded" with elements.length minus one. This operation determine which index of the array will hold the new value e, and allows cyclic wrapping back to the beginning of the array. OK so far (I hope it's not wrong).
But then we come to the line:
if (head == tail) doubleCapacity();
Head and tail are ints. Even if they would equal the same position in the array after being bitwise "anded" (implying the array is full and needs to expand), that doesn't make them equal as ints (which is what is being tested, right?).
So... I don't see how this works.
Can anyone help?
Edited to clarify I'm referring to the index of the array, not any of its elements.