记mod = elements.length = 2^k, a为[-1,module+1]之间的一个整数,那么有: a == -1: a & (mod-1) == mod - 1; 0 <= a < mod: a & (mod - 1) == a a == mod: a & (mod - 1) == 0
/** 将队列的容量变成二倍 * Doubles the capacity of this deque. Call only when full, i.e., * when head and tail have wrapped around to become equal. */ privatevoiddoubleCapacity() { assert head == tail; intp= head; intn= elements.length; intr= n - p; // number of elements to the right of p intnewCapacity= n << 1; if (newCapacity < 0) thrownewIllegalStateException("Sorry, deque too big"); Object[] a = newObject[newCapacity]; System.arraycopy(elements, p, a, 0, r); System.arraycopy(elements, 0, a, r, p); elements = a; head = 0; tail = n;
/** * Inserts the specified element at the end of this deque. */ publicvoidaddLast(E e) { if (e == null) thrownewNullPointerException(); elements[tail] = e; if ( (tail = (tail + 1) & (elements.length - 1)) == head) //在tail位置后面加入元素 doubleCapacity(); }
/** * Returns the number of elements in this deque. */ publicintsize() { return (tail - head) & (elements.length - 1); } /** * Returns an array containing all of the elements in this deque * in proper sequence (from first to last element). */ public Object[] toArray() { return copyElements(newObject[size()]); }
publicvoidclear() {//清空操作 inth= head; intt= tail; if (h != t) { // head != tail 表示队列元素 不为空 head = tail = 0;//设置head 和 tail 初始状态 inti= h; intmask= elements.length - 1; do { elements[i] = null;//配合循环将所有元素设置为null i = (i + 1) & mask; } while (i != t); } } //遍历集合,正向遍历,从head -- tail public Iterator<E> iterator() { returnnewDeqIterator(); } //反向遍历 public Iterator<E> descendingIterator() { returnnewDescendingIterator(); } publicbooleancontains(Object o) {//判断队列是否包含该元素 if (o == null) returnfalse; intmask= elements.length - 1; inti= head; E x; while ( (x = elements[i]) != null) {//从head元素向后猪哥判断,是否equals if (o.equals(x)) returntrue; i = (i + 1) & mask; } returnfalse; } publicintsize() {//获取队列元素个数,(tail - head) & (elements.length - 1)保证大小在有效范围内。 return (tail - head) & (elements.length - 1); } publicbooleanisEmpty() {//入队操作,tail+=1;出队操作head+=1;当一直出队元素的时候,head一直+,会==tail,此时head==tail都指向null元素。 return head == tail; }