publicArrayDeque(Collection<? extends E> c) { allocateElements(c.size()); addAll(c); }
privatestaticintcalculateSize(int numElements) { // 根据给定的数字,计算一个刚好比它大的2次幂 intinitialCapacity= MIN_INITIAL_CAPACITY; // Find the best power of two to hold elements. // Tests "<=" because arrays aren't kept full. if (numElements >= initialCapacity) { initialCapacity = numElements; initialCapacity |= (initialCapacity >>> 1); initialCapacity |= (initialCapacity >>> 2); initialCapacity |= (initialCapacity >>> 4); initialCapacity |= (initialCapacity >>> 8); initialCapacity |= (initialCapacity >>> 16); initialCapacity++;
if (initialCapacity < 0) // Too many elements, must back off initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements } return initialCapacity; }
privatevoidallocateElements(int numElements) { elements = newObject[calculateSize(numElements)]; }
publicvoidaddFirst(E e) { if (e == null) thrownewNullPointerException(); elements[head = (head - 1) & (elements.length - 1)] = e; if (head == tail) doubleCapacity(); }
publicvoidaddLast(E e) { if (e == null) thrownewNullPointerException(); elements[tail] = e; if ( (tail = (tail + 1) & (elements.length - 1)) == head) doubleCapacity(); }
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; }
public E pollFirst() { inth= head; @SuppressWarnings("unchecked") Eresult= (E) elements[h]; // Element is null if deque empty if (result == null) returnnull; elements[h] = null; // Must null out slot head = (h + 1) & (elements.length - 1); return result; }
public E pollLast() { intt= (tail - 1) & (elements.length - 1); @SuppressWarnings("unchecked") Eresult= (E) elements[t]; if (result == null) returnnull; elements[t] = null; tail = t; return result; }
peekFirst()、peekLast()
1 2 3 4 5 6 7 8
public E peekFirst() { // elements[head] is null if deque empty return (E) elements[head]; }
public E peekLast() { return (E) elements[(tail - 1) & (elements.length - 1)]; }