我一直在尋找的ArrayDeque.contains(Object o)
的源代碼時,我發現這個實現:你爲什麼要用i =(i + 1)&mask來遞增,mask是0b1111?
/**
* Returns {@code true} if this deque contains the specified element.
* More formally, returns {@code true} if and only if this deque contains
* at least one element {@code e} such that {@code o.equals(e)}.
*
* @param o object to be checked for containment in this deque
* @return {@code true} if this deque contains the specified element
*/
public boolean contains(Object o) {
if (o == null)
return false;
int mask = elements.length - 1;
int i = head;
Object x;
while ((x = elements[i]) != null) {
if (o.equals(x))
return true;
i = (i + 1) & mask;
}
return false;
}
這裏,數組的大小是2的指數,所以mask
應與全1的二進制數。在我看來,i = (i + 1) & mask
與i = i + 1
完全相同。有誰能告訴我爲什麼這樣實施?
它將'i'限制爲小於數組大小......如果'i'到達數組末尾,它將繼續在開始... –