2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 * This code is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 2 only, as
6 * published by the Free Software Foundation. Oracle designates this
7 * particular file as subject to the "Classpath" exception as provided
8 * by Oracle in the LICENSE file that accompanied this code.
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
26 * This file is available under and governed by the GNU General Public
27 * License version 2 only, as published by the Free Software Foundation.
28 * However, the following notice accompanied the original version of this
31 * Written by Josh Bloch of Google Inc. and released to the public domain,
32 * as explained at http://creativecommons.org/publicdomain/zero/1.0/.
39 * Resizable-array implementation of the {@link Deque} interface. Array
40 * deques have no capacity restrictions; they grow as necessary to support
41 * usage. They are not thread-safe; in the absence of external
42 * synchronization, they do not support concurrent access by multiple threads.
43 * Null elements are prohibited. This class is likely to be faster than
44 * {@link Stack} when used as a stack, and faster than {@link LinkedList}
45 * when used as a queue.
47 * <p>Most <tt>ArrayDeque</tt> operations run in amortized constant time.
48 * Exceptions include {@link #remove(Object) remove}, {@link
49 * #removeFirstOccurrence removeFirstOccurrence}, {@link #removeLastOccurrence
50 * removeLastOccurrence}, {@link #contains contains}, {@link #iterator
51 * iterator.remove()}, and the bulk operations, all of which run in linear
54 * <p>The iterators returned by this class's <tt>iterator</tt> method are
55 * <i>fail-fast</i>: If the deque is modified at any time after the iterator
56 * is created, in any way except through the iterator's own <tt>remove</tt>
57 * method, the iterator will generally throw a {@link
58 * ConcurrentModificationException}. Thus, in the face of concurrent
59 * modification, the iterator fails quickly and cleanly, rather than risking
60 * arbitrary, non-deterministic behavior at an undetermined time in the
63 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
64 * as it is, generally speaking, impossible to make any hard guarantees in the
65 * presence of unsynchronized concurrent modification. Fail-fast iterators
66 * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
67 * Therefore, it would be wrong to write a program that depended on this
68 * exception for its correctness: <i>the fail-fast behavior of iterators
69 * should be used only to detect bugs.</i>
71 * <p>This class and its iterator implement all of the
72 * <em>optional</em> methods of the {@link Collection} and {@link
73 * Iterator} interfaces.
75 * <p>This class is a member of the
76 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
77 * Java Collections Framework</a>.
79 * @author Josh Bloch and Doug Lea
81 * @param <E> the type of elements held in this collection
83 public class ArrayDeque<E> extends AbstractCollection<E>
84 implements Deque<E>, Cloneable, Serializable
87 * The array in which the elements of the deque are stored.
88 * The capacity of the deque is the length of this array, which is
89 * always a power of two. The array is never allowed to become
90 * full, except transiently within an addX method where it is
91 * resized (see doubleCapacity) immediately upon becoming full,
92 * thus avoiding head and tail wrapping around to equal each
93 * other. We also guarantee that all array cells not holding
94 * deque elements are always null.
96 private transient E[] elements;
99 * The index of the element at the head of the deque (which is the
100 * element that would be removed by remove() or pop()); or an
101 * arbitrary number equal to tail if the deque is empty.
103 private transient int head;
106 * The index at which the next element would be added to the tail
107 * of the deque (via addLast(E), add(E), or push(E)).
109 private transient int tail;
112 * The minimum capacity that we'll use for a newly created deque.
113 * Must be a power of 2.
115 private static final int MIN_INITIAL_CAPACITY = 8;
117 // ****** Array allocation and resizing utilities ******
120 * Allocate empty array to hold the given number of elements.
122 * @param numElements the number of elements to hold
124 private void allocateElements(int numElements) {
125 int initialCapacity = MIN_INITIAL_CAPACITY;
126 // Find the best power of two to hold elements.
127 // Tests "<=" because arrays aren't kept full.
128 if (numElements >= initialCapacity) {
129 initialCapacity = numElements;
130 initialCapacity |= (initialCapacity >>> 1);
131 initialCapacity |= (initialCapacity >>> 2);
132 initialCapacity |= (initialCapacity >>> 4);
133 initialCapacity |= (initialCapacity >>> 8);
134 initialCapacity |= (initialCapacity >>> 16);
137 if (initialCapacity < 0) // Too many elements, must back off
138 initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
140 elements = (E[]) new Object[initialCapacity];
144 * Double the capacity of this deque. Call only when full, i.e.,
145 * when head and tail have wrapped around to become equal.
147 private void doubleCapacity() {
150 int n = elements.length;
151 int r = n - p; // number of elements to the right of p
152 int newCapacity = n << 1;
154 throw new IllegalStateException("Sorry, deque too big");
155 Object[] a = new Object[newCapacity];
156 System.arraycopy(elements, p, a, 0, r);
157 System.arraycopy(elements, 0, a, r, p);
164 * Copies the elements from our element array into the specified array,
165 * in order (from first to last element in the deque). It is assumed
166 * that the array is large enough to hold all elements in the deque.
168 * @return its argument
170 private <T> T[] copyElements(T[] a) {
172 System.arraycopy(elements, head, a, 0, size());
173 } else if (head > tail) {
174 int headPortionLen = elements.length - head;
175 System.arraycopy(elements, head, a, 0, headPortionLen);
176 System.arraycopy(elements, 0, a, headPortionLen, tail);
182 * Constructs an empty array deque with an initial capacity
183 * sufficient to hold 16 elements.
185 public ArrayDeque() {
186 elements = (E[]) new Object[16];
190 * Constructs an empty array deque with an initial capacity
191 * sufficient to hold the specified number of elements.
193 * @param numElements lower bound on initial capacity of the deque
195 public ArrayDeque(int numElements) {
196 allocateElements(numElements);
200 * Constructs a deque containing the elements of the specified
201 * collection, in the order they are returned by the collection's
202 * iterator. (The first element returned by the collection's
203 * iterator becomes the first element, or <i>front</i> of the
206 * @param c the collection whose elements are to be placed into the deque
207 * @throws NullPointerException if the specified collection is null
209 public ArrayDeque(Collection<? extends E> c) {
210 allocateElements(c.size());
214 // The main insertion and extraction methods are addFirst,
215 // addLast, pollFirst, pollLast. The other methods are defined in
219 * Inserts the specified element at the front of this deque.
221 * @param e the element to add
222 * @throws NullPointerException if the specified element is null
224 public void addFirst(E e) {
226 throw new NullPointerException();
227 elements[head = (head - 1) & (elements.length - 1)] = e;
233 * Inserts the specified element at the end of this deque.
235 * <p>This method is equivalent to {@link #add}.
237 * @param e the element to add
238 * @throws NullPointerException if the specified element is null
240 public void addLast(E e) {
242 throw new NullPointerException();
244 if ( (tail = (tail + 1) & (elements.length - 1)) == head)
249 * Inserts the specified element at the front of this deque.
251 * @param e the element to add
252 * @return <tt>true</tt> (as specified by {@link Deque#offerFirst})
253 * @throws NullPointerException if the specified element is null
255 public boolean offerFirst(E e) {
261 * Inserts the specified element at the end of this deque.
263 * @param e the element to add
264 * @return <tt>true</tt> (as specified by {@link Deque#offerLast})
265 * @throws NullPointerException if the specified element is null
267 public boolean offerLast(E e) {
273 * @throws NoSuchElementException {@inheritDoc}
275 public E removeFirst() {
278 throw new NoSuchElementException();
283 * @throws NoSuchElementException {@inheritDoc}
285 public E removeLast() {
288 throw new NoSuchElementException();
292 public E pollFirst() {
294 E result = elements[h]; // Element is null if deque empty
297 elements[h] = null; // Must null out slot
298 head = (h + 1) & (elements.length - 1);
302 public E pollLast() {
303 int t = (tail - 1) & (elements.length - 1);
304 E result = elements[t];
313 * @throws NoSuchElementException {@inheritDoc}
315 public E getFirst() {
316 E x = elements[head];
318 throw new NoSuchElementException();
323 * @throws NoSuchElementException {@inheritDoc}
326 E x = elements[(tail - 1) & (elements.length - 1)];
328 throw new NoSuchElementException();
332 public E peekFirst() {
333 return elements[head]; // elements[head] is null if deque empty
336 public E peekLast() {
337 return elements[(tail - 1) & (elements.length - 1)];
341 * Removes the first occurrence of the specified element in this
342 * deque (when traversing the deque from head to tail).
343 * If the deque does not contain the element, it is unchanged.
344 * More formally, removes the first element <tt>e</tt> such that
345 * <tt>o.equals(e)</tt> (if such an element exists).
346 * Returns <tt>true</tt> if this deque contained the specified element
347 * (or equivalently, if this deque changed as a result of the call).
349 * @param o element to be removed from this deque, if present
350 * @return <tt>true</tt> if the deque contained the specified element
352 public boolean removeFirstOccurrence(Object o) {
355 int mask = elements.length - 1;
358 while ( (x = elements[i]) != null) {
369 * Removes the last occurrence of the specified element in this
370 * deque (when traversing the deque from head to tail).
371 * If the deque does not contain the element, it is unchanged.
372 * More formally, removes the last element <tt>e</tt> such that
373 * <tt>o.equals(e)</tt> (if such an element exists).
374 * Returns <tt>true</tt> if this deque contained the specified element
375 * (or equivalently, if this deque changed as a result of the call).
377 * @param o element to be removed from this deque, if present
378 * @return <tt>true</tt> if the deque contained the specified element
380 public boolean removeLastOccurrence(Object o) {
383 int mask = elements.length - 1;
384 int i = (tail - 1) & mask;
386 while ( (x = elements[i]) != null) {
396 // *** Queue methods ***
399 * Inserts the specified element at the end of this deque.
401 * <p>This method is equivalent to {@link #addLast}.
403 * @param e the element to add
404 * @return <tt>true</tt> (as specified by {@link Collection#add})
405 * @throws NullPointerException if the specified element is null
407 public boolean add(E e) {
413 * Inserts the specified element at the end of this deque.
415 * <p>This method is equivalent to {@link #offerLast}.
417 * @param e the element to add
418 * @return <tt>true</tt> (as specified by {@link Queue#offer})
419 * @throws NullPointerException if the specified element is null
421 public boolean offer(E e) {
426 * Retrieves and removes the head of the queue represented by this deque.
428 * This method differs from {@link #poll poll} only in that it throws an
429 * exception if this deque is empty.
431 * <p>This method is equivalent to {@link #removeFirst}.
433 * @return the head of the queue represented by this deque
434 * @throws NoSuchElementException {@inheritDoc}
437 return removeFirst();
441 * Retrieves and removes the head of the queue represented by this deque
442 * (in other words, the first element of this deque), or returns
443 * <tt>null</tt> if this deque is empty.
445 * <p>This method is equivalent to {@link #pollFirst}.
447 * @return the head of the queue represented by this deque, or
448 * <tt>null</tt> if this deque is empty
455 * Retrieves, but does not remove, the head of the queue represented by
456 * this deque. This method differs from {@link #peek peek} only in
457 * that it throws an exception if this deque is empty.
459 * <p>This method is equivalent to {@link #getFirst}.
461 * @return the head of the queue represented by this deque
462 * @throws NoSuchElementException {@inheritDoc}
469 * Retrieves, but does not remove, the head of the queue represented by
470 * this deque, or returns <tt>null</tt> if this deque is empty.
472 * <p>This method is equivalent to {@link #peekFirst}.
474 * @return the head of the queue represented by this deque, or
475 * <tt>null</tt> if this deque is empty
481 // *** Stack methods ***
484 * Pushes an element onto the stack represented by this deque. In other
485 * words, inserts the element at the front of this deque.
487 * <p>This method is equivalent to {@link #addFirst}.
489 * @param e the element to push
490 * @throws NullPointerException if the specified element is null
492 public void push(E e) {
497 * Pops an element from the stack represented by this deque. In other
498 * words, removes and returns the first element of this deque.
500 * <p>This method is equivalent to {@link #removeFirst()}.
502 * @return the element at the front of this deque (which is the top
503 * of the stack represented by this deque)
504 * @throws NoSuchElementException {@inheritDoc}
507 return removeFirst();
510 private void checkInvariants() {
511 assert elements[tail] == null;
512 assert head == tail ? elements[head] == null :
513 (elements[head] != null &&
514 elements[(tail - 1) & (elements.length - 1)] != null);
515 assert elements[(head - 1) & (elements.length - 1)] == null;
519 * Removes the element at the specified position in the elements array,
520 * adjusting head and tail as necessary. This can result in motion of
521 * elements backwards or forwards in the array.
523 * <p>This method is called delete rather than remove to emphasize
524 * that its semantics differ from those of {@link List#remove(int)}.
526 * @return true if elements moved backwards
528 private boolean delete(int i) {
530 final E[] elements = this.elements;
531 final int mask = elements.length - 1;
534 final int front = (i - h) & mask;
535 final int back = (t - i) & mask;
537 // Invariant: head <= i < tail mod circularity
538 if (front >= ((t - h) & mask))
539 throw new ConcurrentModificationException();
541 // Optimize for least element motion
544 System.arraycopy(elements, h, elements, h + 1, front);
545 } else { // Wrap around
546 System.arraycopy(elements, 0, elements, 1, i);
547 elements[0] = elements[mask];
548 System.arraycopy(elements, h, elements, h + 1, mask - h);
551 head = (h + 1) & mask;
554 if (i < t) { // Copy the null tail as well
555 System.arraycopy(elements, i + 1, elements, i, back);
557 } else { // Wrap around
558 System.arraycopy(elements, i + 1, elements, i, mask - i);
559 elements[mask] = elements[0];
560 System.arraycopy(elements, 1, elements, 0, t);
561 tail = (t - 1) & mask;
567 // *** Collection Methods ***
570 * Returns the number of elements in this deque.
572 * @return the number of elements in this deque
575 return (tail - head) & (elements.length - 1);
579 * Returns <tt>true</tt> if this deque contains no elements.
581 * @return <tt>true</tt> if this deque contains no elements
583 public boolean isEmpty() {
588 * Returns an iterator over the elements in this deque. The elements
589 * will be ordered from first (head) to last (tail). This is the same
590 * order that elements would be dequeued (via successive calls to
591 * {@link #remove} or popped (via successive calls to {@link #pop}).
593 * @return an iterator over the elements in this deque
595 public Iterator<E> iterator() {
596 return new DeqIterator();
599 public Iterator<E> descendingIterator() {
600 return new DescendingIterator();
603 private class DeqIterator implements Iterator<E> {
605 * Index of element to be returned by subsequent call to next.
607 private int cursor = head;
610 * Tail recorded at construction (also in remove), to stop
611 * iterator and also to check for comodification.
613 private int fence = tail;
616 * Index of element returned by most recent call to next.
617 * Reset to -1 if element is deleted by a call to remove.
619 private int lastRet = -1;
621 public boolean hasNext() {
622 return cursor != fence;
627 throw new NoSuchElementException();
628 E result = elements[cursor];
629 // This check doesn't catch all possible comodifications,
630 // but does catch the ones that corrupt traversal
631 if (tail != fence || result == null)
632 throw new ConcurrentModificationException();
634 cursor = (cursor + 1) & (elements.length - 1);
638 public void remove() {
640 throw new IllegalStateException();
641 if (delete(lastRet)) { // if left-shifted, undo increment in next()
642 cursor = (cursor - 1) & (elements.length - 1);
649 private class DescendingIterator implements Iterator<E> {
651 * This class is nearly a mirror-image of DeqIterator, using
652 * tail instead of head for initial cursor, and head instead of
655 private int cursor = tail;
656 private int fence = head;
657 private int lastRet = -1;
659 public boolean hasNext() {
660 return cursor != fence;
665 throw new NoSuchElementException();
666 cursor = (cursor - 1) & (elements.length - 1);
667 E result = elements[cursor];
668 if (head != fence || result == null)
669 throw new ConcurrentModificationException();
674 public void remove() {
676 throw new IllegalStateException();
677 if (!delete(lastRet)) {
678 cursor = (cursor + 1) & (elements.length - 1);
686 * Returns <tt>true</tt> if this deque contains the specified element.
687 * More formally, returns <tt>true</tt> if and only if this deque contains
688 * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
690 * @param o object to be checked for containment in this deque
691 * @return <tt>true</tt> if this deque contains the specified element
693 public boolean contains(Object o) {
696 int mask = elements.length - 1;
699 while ( (x = elements[i]) != null) {
708 * Removes a single instance of the specified element from this deque.
709 * If the deque does not contain the element, it is unchanged.
710 * More formally, removes the first element <tt>e</tt> such that
711 * <tt>o.equals(e)</tt> (if such an element exists).
712 * Returns <tt>true</tt> if this deque contained the specified element
713 * (or equivalently, if this deque changed as a result of the call).
715 * <p>This method is equivalent to {@link #removeFirstOccurrence}.
717 * @param o element to be removed from this deque, if present
718 * @return <tt>true</tt> if this deque contained the specified element
720 public boolean remove(Object o) {
721 return removeFirstOccurrence(o);
725 * Removes all of the elements from this deque.
726 * The deque will be empty after this call returns.
728 public void clear() {
731 if (h != t) { // clear all cells
734 int mask = elements.length - 1;
743 * Returns an array containing all of the elements in this deque
744 * in proper sequence (from first to last element).
746 * <p>The returned array will be "safe" in that no references to it are
747 * maintained by this deque. (In other words, this method must allocate
748 * a new array). The caller is thus free to modify the returned array.
750 * <p>This method acts as bridge between array-based and collection-based
753 * @return an array containing all of the elements in this deque
755 public Object[] toArray() {
756 return copyElements(new Object[size()]);
760 * Returns an array containing all of the elements in this deque in
761 * proper sequence (from first to last element); the runtime type of the
762 * returned array is that of the specified array. If the deque fits in
763 * the specified array, it is returned therein. Otherwise, a new array
764 * is allocated with the runtime type of the specified array and the
765 * size of this deque.
767 * <p>If this deque fits in the specified array with room to spare
768 * (i.e., the array has more elements than this deque), the element in
769 * the array immediately following the end of the deque is set to
772 * <p>Like the {@link #toArray()} method, this method acts as bridge between
773 * array-based and collection-based APIs. Further, this method allows
774 * precise control over the runtime type of the output array, and may,
775 * under certain circumstances, be used to save allocation costs.
777 * <p>Suppose <tt>x</tt> is a deque known to contain only strings.
778 * The following code can be used to dump the deque into a newly
779 * allocated array of <tt>String</tt>:
782 * String[] y = x.toArray(new String[0]);</pre>
784 * Note that <tt>toArray(new Object[0])</tt> is identical in function to
785 * <tt>toArray()</tt>.
787 * @param a the array into which the elements of the deque are to
788 * be stored, if it is big enough; otherwise, a new array of the
789 * same runtime type is allocated for this purpose
790 * @return an array containing all of the elements in this deque
791 * @throws ArrayStoreException if the runtime type of the specified array
792 * is not a supertype of the runtime type of every element in
794 * @throws NullPointerException if the specified array is null
796 public <T> T[] toArray(T[] a) {
799 a = (T[])java.lang.reflect.Array.newInstance(
800 a.getClass().getComponentType(), size);
807 // *** Object methods ***
810 * Returns a copy of this deque.
812 * @return a copy of this deque
814 public ArrayDeque<E> clone() {
816 ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
817 result.elements = Arrays.copyOf(elements, elements.length);
820 } catch (CloneNotSupportedException e) {
821 throw new AssertionError();
826 * Appease the serialization gods.
828 private static final long serialVersionUID = 2340985798034038923L;