The functionality of the next line is basically (head - 1) MODULO (elements.length) , so subtracting 1 from the head leads to the maximum possible value instead of -1 when head == 0 .
head = (head - 1) & (elements.length - 1)
10 does not correspond to the length of elements , according to the implementation of elements.length always has a force of two. If this is not the case, the operation will not work.
Understanding why this works requires knowledge of bit operations. Assuming elements.length == 16 == 00010000b and that for simplicity values ββis 8 bits instead of the actual 32:
(elements.length - 1) used to get a bit mask with a length of n bits, where 2 ^ n is the current length of the elements. (elements.length - 1) == 15 == 00001111b in this case.
If head > 0 and head < elements.length (which is given), then (head - 1) & (elements.length - 1) == (head - 1) , since ANDing does nothing with 1s.
If head == 0 , head - 1 == -1 == 11111111b . (An integer designation with two additions, although you can also think of it as a simple integer overflow.) ANDing with a mask (head - 1) & 00001111b == 11111111b & 00001111b == 00001111b == 15 , which is the required value.
source share