2 * Written by Josh Bloch of Google Inc. and released to the public domain,
3 * as explained at http://creativecommons.org/licenses/publicdomain.
10 * Resizable-array implementation of the {@link Deque} interface. Array
11 * deques have no capacity restrictions; they grow as necessary to support
12 * usage. They are not thread-safe; in the absence of external
13 * synchronization, they do not support concurrent access by multiple threads.
14 * Null elements are prohibited. This class is likely to be faster than
15 * {@link Stack} when used as a stack, and faster than {@link LinkedList}
16 * when used as a queue.
18 * <p>Most <tt>ArrayDeque</tt> operations run in amortized constant time.
19 * Exceptions include {@link #remove(Object) remove}, {@link
20 * #removeFirstOccurrence removeFirstOccurrence}, {@link #removeLastOccurrence
21 * removeLastOccurrence}, {@link #contains contains}, {@link #iterator
22 * iterator.remove()}, and the bulk operations, all of which run in linear
25 * <p>The iterators returned by this class's <tt>iterator</tt> method are
26 * <i>fail-fast</i>: If the deque is modified at any time after the iterator
27 * is created, in any way except through the iterator's own <tt>remove</tt>
28 * method, the iterator will generally throw a {@link
29 * ConcurrentModificationException}. Thus, in the face of concurrent
30 * modification, the iterator fails quickly and cleanly, rather than risking
31 * arbitrary, non-deterministic behavior at an undetermined time in the
34 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
35 * as it is, generally speaking, impossible to make any hard guarantees in the
36 * presence of unsynchronized concurrent modification. Fail-fast iterators
37 * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
38 * Therefore, it would be wrong to write a program that depended on this
39 * exception for its correctness: <i>the fail-fast behavior of iterators
40 * should be used only to detect bugs.</i>
42 * <p>This class and its iterator implement all of the
43 * <em>optional</em> methods of the {@link Collection} and {@link
44 * Iterator} interfaces.
46 * <p>This class is a member of the
47 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
48 * Java Collections Framework</a>.
50 * @author Josh Bloch and Doug Lea
52 * @param <E> the type of elements held in this collection
54 public class ArrayDeque<E> extends AbstractCollection<E>
55 implements Deque<E>, Cloneable, Serializable
58 * The array in which the elements of the deque are stored.
59 * The capacity of the deque is the length of this array, which is
60 * always a power of two. The array is never allowed to become
61 * full, except transiently within an addX method where it is
62 * resized (see doubleCapacity) immediately upon becoming full,
63 * thus avoiding head and tail wrapping around to equal each
64 * other. We also guarantee that all array cells not holding
65 * deque elements are always null.
67 private transient E[] elements;
70 * The index of the element at the head of the deque (which is the
71 * element that would be removed by remove() or pop()); or an
72 * arbitrary number equal to tail if the deque is empty.
74 private transient int head;
77 * The index at which the next element would be added to the tail
78 * of the deque (via addLast(E), add(E), or push(E)).
80 private transient int tail;
83 * The minimum capacity that we'll use for a newly created deque.
84 * Must be a power of 2.
86 private static final int MIN_INITIAL_CAPACITY = 8;
88 // ****** Array allocation and resizing utilities ******
91 * Allocate empty array to hold the given number of elements.
93 * @param numElements the number of elements to hold
95 private void allocateElements(int numElements) {
96 int initialCapacity = MIN_INITIAL_CAPACITY;
97 // Find the best power of two to hold elements.
98 // Tests "<=" because arrays aren't kept full.
99 if (numElements >= initialCapacity) {
100 initialCapacity = numElements;
101 initialCapacity |= (initialCapacity >>> 1);
102 initialCapacity |= (initialCapacity >>> 2);
103 initialCapacity |= (initialCapacity >>> 4);
104 initialCapacity |= (initialCapacity >>> 8);
105 initialCapacity |= (initialCapacity >>> 16);
108 if (initialCapacity < 0) // Too many elements, must back off
109 initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
111 elements = (E[]) new Object[initialCapacity];
115 * Double the capacity of this deque. Call only when full, i.e.,
116 * when head and tail have wrapped around to become equal.
118 private void doubleCapacity() {
121 int n = elements.length;
122 int r = n - p; // number of elements to the right of p
123 int newCapacity = n << 1;
125 throw new IllegalStateException("Sorry, deque too big");
126 Object[] a = new Object[newCapacity];
127 System.arraycopy(elements, p, a, 0, r);
128 System.arraycopy(elements, 0, a, r, p);
135 * Copies the elements from our element array into the specified array,
136 * in order (from first to last element in the deque). It is assumed
137 * that the array is large enough to hold all elements in the deque.
139 * @return its argument
141 private <T> T[] copyElements(T[] a) {
143 System.arraycopy(elements, head, a, 0, size());
144 } else if (head > tail) {
145 int headPortionLen = elements.length - head;
146 System.arraycopy(elements, head, a, 0, headPortionLen);
147 System.arraycopy(elements, 0, a, headPortionLen, tail);
153 * Constructs an empty array deque with an initial capacity
154 * sufficient to hold 16 elements.
156 public ArrayDeque() {
157 elements = (E[]) new Object[16];
161 * Constructs an empty array deque with an initial capacity
162 * sufficient to hold the specified number of elements.
164 * @param numElements lower bound on initial capacity of the deque
166 public ArrayDeque(int numElements) {
167 allocateElements(numElements);
171 * Constructs a deque containing the elements of the specified
172 * collection, in the order they are returned by the collection's
173 * iterator. (The first element returned by the collection's
174 * iterator becomes the first element, or <i>front</i> of the
177 * @param c the collection whose elements are to be placed into the deque
178 * @throws NullPointerException if the specified collection is null
180 public ArrayDeque(Collection<? extends E> c) {
181 allocateElements(c.size());
185 // The main insertion and extraction methods are addFirst,
186 // addLast, pollFirst, pollLast. The other methods are defined in
190 * Inserts the specified element at the front of this deque.
192 * @param e the element to add
193 * @throws NullPointerException if the specified element is null
195 public void addFirst(E e) {
197 throw new NullPointerException();
198 elements[head = (head - 1) & (elements.length - 1)] = e;
204 * Inserts the specified element at the end of this deque.
206 * <p>This method is equivalent to {@link #add}.
208 * @param e the element to add
209 * @throws NullPointerException if the specified element is null
211 public void addLast(E e) {
213 throw new NullPointerException();
215 if ( (tail = (tail + 1) & (elements.length - 1)) == head)
220 * Inserts the specified element at the front of this deque.
222 * @param e the element to add
223 * @return <tt>true</tt> (as specified by {@link Deque#offerFirst})
224 * @throws NullPointerException if the specified element is null
226 public boolean offerFirst(E e) {
232 * Inserts the specified element at the end of this deque.
234 * @param e the element to add
235 * @return <tt>true</tt> (as specified by {@link Deque#offerLast})
236 * @throws NullPointerException if the specified element is null
238 public boolean offerLast(E e) {
244 * @throws NoSuchElementException {@inheritDoc}
246 public E removeFirst() {
249 throw new NoSuchElementException();
254 * @throws NoSuchElementException {@inheritDoc}
256 public E removeLast() {
259 throw new NoSuchElementException();
263 public E pollFirst() {
265 E result = elements[h]; // Element is null if deque empty
268 elements[h] = null; // Must null out slot
269 head = (h + 1) & (elements.length - 1);
273 public E pollLast() {
274 int t = (tail - 1) & (elements.length - 1);
275 E result = elements[t];
284 * @throws NoSuchElementException {@inheritDoc}
286 public E getFirst() {
287 E x = elements[head];
289 throw new NoSuchElementException();
294 * @throws NoSuchElementException {@inheritDoc}
297 E x = elements[(tail - 1) & (elements.length - 1)];
299 throw new NoSuchElementException();
303 public E peekFirst() {
304 return elements[head]; // elements[head] is null if deque empty
307 public E peekLast() {
308 return elements[(tail - 1) & (elements.length - 1)];
312 * Removes the first occurrence of the specified element in this
313 * deque (when traversing the deque from head to tail).
314 * If the deque does not contain the element, it is unchanged.
315 * More formally, removes the first element <tt>e</tt> such that
316 * <tt>o.equals(e)</tt> (if such an element exists).
317 * Returns <tt>true</tt> if this deque contained the specified element
318 * (or equivalently, if this deque changed as a result of the call).
320 * @param o element to be removed from this deque, if present
321 * @return <tt>true</tt> if the deque contained the specified element
323 public boolean removeFirstOccurrence(Object o) {
326 int mask = elements.length - 1;
329 while ( (x = elements[i]) != null) {
340 * Removes the last occurrence of the specified element in this
341 * deque (when traversing the deque from head to tail).
342 * If the deque does not contain the element, it is unchanged.
343 * More formally, removes the last element <tt>e</tt> such that
344 * <tt>o.equals(e)</tt> (if such an element exists).
345 * Returns <tt>true</tt> if this deque contained the specified element
346 * (or equivalently, if this deque changed as a result of the call).
348 * @param o element to be removed from this deque, if present
349 * @return <tt>true</tt> if the deque contained the specified element
351 public boolean removeLastOccurrence(Object o) {
354 int mask = elements.length - 1;
355 int i = (tail - 1) & mask;
357 while ( (x = elements[i]) != null) {
367 // *** Queue methods ***
370 * Inserts the specified element at the end of this deque.
372 * <p>This method is equivalent to {@link #addLast}.
374 * @param e the element to add
375 * @return <tt>true</tt> (as specified by {@link Collection#add})
376 * @throws NullPointerException if the specified element is null
378 public boolean add(E e) {
384 * Inserts the specified element at the end of this deque.
386 * <p>This method is equivalent to {@link #offerLast}.
388 * @param e the element to add
389 * @return <tt>true</tt> (as specified by {@link Queue#offer})
390 * @throws NullPointerException if the specified element is null
392 public boolean offer(E e) {
397 * Retrieves and removes the head of the queue represented by this deque.
399 * This method differs from {@link #poll poll} only in that it throws an
400 * exception if this deque is empty.
402 * <p>This method is equivalent to {@link #removeFirst}.
404 * @return the head of the queue represented by this deque
405 * @throws NoSuchElementException {@inheritDoc}
408 return removeFirst();
412 * Retrieves and removes the head of the queue represented by this deque
413 * (in other words, the first element of this deque), or returns
414 * <tt>null</tt> if this deque is empty.
416 * <p>This method is equivalent to {@link #pollFirst}.
418 * @return the head of the queue represented by this deque, or
419 * <tt>null</tt> if this deque is empty
426 * Retrieves, but does not remove, the head of the queue represented by
427 * this deque. This method differs from {@link #peek peek} only in
428 * that it throws an exception if this deque is empty.
430 * <p>This method is equivalent to {@link #getFirst}.
432 * @return the head of the queue represented by this deque
433 * @throws NoSuchElementException {@inheritDoc}
440 * Retrieves, but does not remove, the head of the queue represented by
441 * this deque, or returns <tt>null</tt> if this deque is empty.
443 * <p>This method is equivalent to {@link #peekFirst}.
445 * @return the head of the queue represented by this deque, or
446 * <tt>null</tt> if this deque is empty
452 // *** Stack methods ***
455 * Pushes an element onto the stack represented by this deque. In other
456 * words, inserts the element at the front of this deque.
458 * <p>This method is equivalent to {@link #addFirst}.
460 * @param e the element to push
461 * @throws NullPointerException if the specified element is null
463 public void push(E e) {
468 * Pops an element from the stack represented by this deque. In other
469 * words, removes and returns the first element of this deque.
471 * <p>This method is equivalent to {@link #removeFirst()}.
473 * @return the element at the front of this deque (which is the top
474 * of the stack represented by this deque)
475 * @throws NoSuchElementException {@inheritDoc}
478 return removeFirst();
481 private void checkInvariants() {
482 assert elements[tail] == null;
483 assert head == tail ? elements[head] == null :
484 (elements[head] != null &&
485 elements[(tail - 1) & (elements.length - 1)] != null);
486 assert elements[(head - 1) & (elements.length - 1)] == null;
490 * Removes the element at the specified position in the elements array,
491 * adjusting head and tail as necessary. This can result in motion of
492 * elements backwards or forwards in the array.
494 * <p>This method is called delete rather than remove to emphasize
495 * that its semantics differ from those of {@link List#remove(int)}.
497 * @return true if elements moved backwards
499 private boolean delete(int i) {
501 final E[] elements = this.elements;
502 final int mask = elements.length - 1;
505 final int front = (i - h) & mask;
506 final int back = (t - i) & mask;
508 // Invariant: head <= i < tail mod circularity
509 if (front >= ((t - h) & mask))
510 throw new ConcurrentModificationException();
512 // Optimize for least element motion
515 System.arraycopy(elements, h, elements, h + 1, front);
516 } else { // Wrap around
517 System.arraycopy(elements, 0, elements, 1, i);
518 elements[0] = elements[mask];
519 System.arraycopy(elements, h, elements, h + 1, mask - h);
522 head = (h + 1) & mask;
525 if (i < t) { // Copy the null tail as well
526 System.arraycopy(elements, i + 1, elements, i, back);
528 } else { // Wrap around
529 System.arraycopy(elements, i + 1, elements, i, mask - i);
530 elements[mask] = elements[0];
531 System.arraycopy(elements, 1, elements, 0, t);
532 tail = (t - 1) & mask;
538 // *** Collection Methods ***
541 * Returns the number of elements in this deque.
543 * @return the number of elements in this deque
546 return (tail - head) & (elements.length - 1);
550 * Returns <tt>true</tt> if this deque contains no elements.
552 * @return <tt>true</tt> if this deque contains no elements
554 public boolean isEmpty() {
559 * Returns an iterator over the elements in this deque. The elements
560 * will be ordered from first (head) to last (tail). This is the same
561 * order that elements would be dequeued (via successive calls to
562 * {@link #remove} or popped (via successive calls to {@link #pop}).
564 * @return an iterator over the elements in this deque
566 public Iterator<E> iterator() {
567 return new DeqIterator();
570 public Iterator<E> descendingIterator() {
571 return new DescendingIterator();
574 private class DeqIterator implements Iterator<E> {
576 * Index of element to be returned by subsequent call to next.
578 private int cursor = head;
581 * Tail recorded at construction (also in remove), to stop
582 * iterator and also to check for comodification.
584 private int fence = tail;
587 * Index of element returned by most recent call to next.
588 * Reset to -1 if element is deleted by a call to remove.
590 private int lastRet = -1;
592 public boolean hasNext() {
593 return cursor != fence;
598 throw new NoSuchElementException();
599 E result = elements[cursor];
600 // This check doesn't catch all possible comodifications,
601 // but does catch the ones that corrupt traversal
602 if (tail != fence || result == null)
603 throw new ConcurrentModificationException();
605 cursor = (cursor + 1) & (elements.length - 1);
609 public void remove() {
611 throw new IllegalStateException();
612 if (delete(lastRet)) { // if left-shifted, undo increment in next()
613 cursor = (cursor - 1) & (elements.length - 1);
620 private class DescendingIterator implements Iterator<E> {
622 * This class is nearly a mirror-image of DeqIterator, using
623 * tail instead of head for initial cursor, and head instead of
626 private int cursor = tail;
627 private int fence = head;
628 private int lastRet = -1;
630 public boolean hasNext() {
631 return cursor != fence;
636 throw new NoSuchElementException();
637 cursor = (cursor - 1) & (elements.length - 1);
638 E result = elements[cursor];
639 if (head != fence || result == null)
640 throw new ConcurrentModificationException();
645 public void remove() {
647 throw new IllegalStateException();
648 if (!delete(lastRet)) {
649 cursor = (cursor + 1) & (elements.length - 1);
657 * Returns <tt>true</tt> if this deque contains the specified element.
658 * More formally, returns <tt>true</tt> if and only if this deque contains
659 * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
661 * @param o object to be checked for containment in this deque
662 * @return <tt>true</tt> if this deque contains the specified element
664 public boolean contains(Object o) {
667 int mask = elements.length - 1;
670 while ( (x = elements[i]) != null) {
679 * Removes a single instance of the specified element from this deque.
680 * If the deque does not contain the element, it is unchanged.
681 * More formally, removes the first element <tt>e</tt> such that
682 * <tt>o.equals(e)</tt> (if such an element exists).
683 * Returns <tt>true</tt> if this deque contained the specified element
684 * (or equivalently, if this deque changed as a result of the call).
686 * <p>This method is equivalent to {@link #removeFirstOccurrence}.
688 * @param o element to be removed from this deque, if present
689 * @return <tt>true</tt> if this deque contained the specified element
691 public boolean remove(Object o) {
692 return removeFirstOccurrence(o);
696 * Removes all of the elements from this deque.
697 * The deque will be empty after this call returns.
699 public void clear() {
702 if (h != t) { // clear all cells
705 int mask = elements.length - 1;
714 * Returns an array containing all of the elements in this deque
715 * in proper sequence (from first to last element).
717 * <p>The returned array will be "safe" in that no references to it are
718 * maintained by this deque. (In other words, this method must allocate
719 * a new array). The caller is thus free to modify the returned array.
721 * <p>This method acts as bridge between array-based and collection-based
724 * @return an array containing all of the elements in this deque
726 public Object[] toArray() {
727 return copyElements(new Object[size()]);
731 * Returns an array containing all of the elements in this deque in
732 * proper sequence (from first to last element); the runtime type of the
733 * returned array is that of the specified array. If the deque fits in
734 * the specified array, it is returned therein. Otherwise, a new array
735 * is allocated with the runtime type of the specified array and the
736 * size of this deque.
738 * <p>If this deque fits in the specified array with room to spare
739 * (i.e., the array has more elements than this deque), the element in
740 * the array immediately following the end of the deque is set to
743 * <p>Like the {@link #toArray()} method, this method acts as bridge between
744 * array-based and collection-based APIs. Further, this method allows
745 * precise control over the runtime type of the output array, and may,
746 * under certain circumstances, be used to save allocation costs.
748 * <p>Suppose <tt>x</tt> is a deque known to contain only strings.
749 * The following code can be used to dump the deque into a newly
750 * allocated array of <tt>String</tt>:
753 * String[] y = x.toArray(new String[0]);</pre>
755 * Note that <tt>toArray(new Object[0])</tt> is identical in function to
756 * <tt>toArray()</tt>.
758 * @param a the array into which the elements of the deque are to
759 * be stored, if it is big enough; otherwise, a new array of the
760 * same runtime type is allocated for this purpose
761 * @return an array containing all of the elements in this deque
762 * @throws ArrayStoreException if the runtime type of the specified array
763 * is not a supertype of the runtime type of every element in
765 * @throws NullPointerException if the specified array is null
767 public <T> T[] toArray(T[] a) {
770 a = (T[])java.lang.reflect.Array.newInstance(
771 a.getClass().getComponentType(), size);
778 // *** Object methods ***
781 * Returns a copy of this deque.
783 * @return a copy of this deque
785 public ArrayDeque<E> clone() {
787 ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
788 // Classpath local: we don't have Arrays.copyOf yet.
789 // result.elements = Arrays.copyOf(elements, elements.length);
790 result.elements = elements.clone();
793 } catch (CloneNotSupportedException e) {
794 throw new AssertionError();
799 * Appease the serialization gods.
801 private static final long serialVersionUID = 2340985798034038923L;
804 * Serialize this deque.
806 * @serialData The current size (<tt>int</tt>) of the deque,
807 * followed by all of its elements (each an object reference) in
808 * first-to-last order.
810 private void writeObject(ObjectOutputStream s) throws IOException {
811 s.defaultWriteObject();
816 // Write out elements in order.
817 int mask = elements.length - 1;
818 for (int i = head; i != tail; i = (i + 1) & mask)
819 s.writeObject(elements[i]);
823 * Deserialize this deque.
825 private void readObject(ObjectInputStream s)
826 throws IOException, ClassNotFoundException {
827 s.defaultReadObject();
829 // Read in size and allocate array
830 int size = s.readInt();
831 allocateElements(size);
835 // Read in all elements in the proper order.
836 for (int i = 0; i < size; i++)
837 elements[i] = (E)s.readObject();