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/.
37 import org.apidesign.bck2brwsr.emul.lang.System;
40 * Resizable-array implementation of the {@link Deque} interface. Array
41 * deques have no capacity restrictions; they grow as necessary to support
42 * usage. They are not thread-safe; in the absence of external
43 * synchronization, they do not support concurrent access by multiple threads.
44 * Null elements are prohibited. This class is likely to be faster than
45 * {@link Stack} when used as a stack, and faster than {@link LinkedList}
46 * when used as a queue.
48 * <p>Most <tt>ArrayDeque</tt> operations run in amortized constant time.
49 * Exceptions include {@link #remove(Object) remove}, {@link
50 * #removeFirstOccurrence removeFirstOccurrence}, {@link #removeLastOccurrence
51 * removeLastOccurrence}, {@link #contains contains}, {@link #iterator
52 * iterator.remove()}, and the bulk operations, all of which run in linear
55 * <p>The iterators returned by this class's <tt>iterator</tt> method are
56 * <i>fail-fast</i>: If the deque is modified at any time after the iterator
57 * is created, in any way except through the iterator's own <tt>remove</tt>
58 * method, the iterator will generally throw a {@link
59 * ConcurrentModificationException}. Thus, in the face of concurrent
60 * modification, the iterator fails quickly and cleanly, rather than risking
61 * arbitrary, non-deterministic behavior at an undetermined time in the
64 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
65 * as it is, generally speaking, impossible to make any hard guarantees in the
66 * presence of unsynchronized concurrent modification. Fail-fast iterators
67 * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
68 * Therefore, it would be wrong to write a program that depended on this
69 * exception for its correctness: <i>the fail-fast behavior of iterators
70 * should be used only to detect bugs.</i>
72 * <p>This class and its iterator implement all of the
73 * <em>optional</em> methods of the {@link Collection} and {@link
74 * Iterator} interfaces.
76 * <p>This class is a member of the
77 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
78 * Java Collections Framework</a>.
80 * @author Josh Bloch and Doug Lea
82 * @param <E> the type of elements held in this collection
84 public class ArrayDeque<E> extends AbstractCollection<E>
85 implements Deque<E>, Cloneable, Serializable
88 * The array in which the elements of the deque are stored.
89 * The capacity of the deque is the length of this array, which is
90 * always a power of two. The array is never allowed to become
91 * full, except transiently within an addX method where it is
92 * resized (see doubleCapacity) immediately upon becoming full,
93 * thus avoiding head and tail wrapping around to equal each
94 * other. We also guarantee that all array cells not holding
95 * deque elements are always null.
97 private transient E[] elements;
100 * The index of the element at the head of the deque (which is the
101 * element that would be removed by remove() or pop()); or an
102 * arbitrary number equal to tail if the deque is empty.
104 private transient int head;
107 * The index at which the next element would be added to the tail
108 * of the deque (via addLast(E), add(E), or push(E)).
110 private transient int tail;
113 * The minimum capacity that we'll use for a newly created deque.
114 * Must be a power of 2.
116 private static final int MIN_INITIAL_CAPACITY = 8;
118 // ****** Array allocation and resizing utilities ******
121 * Allocate empty array to hold the given number of elements.
123 * @param numElements the number of elements to hold
125 private void allocateElements(int numElements) {
126 int initialCapacity = MIN_INITIAL_CAPACITY;
127 // Find the best power of two to hold elements.
128 // Tests "<=" because arrays aren't kept full.
129 if (numElements >= initialCapacity) {
130 initialCapacity = numElements;
131 initialCapacity |= (initialCapacity >>> 1);
132 initialCapacity |= (initialCapacity >>> 2);
133 initialCapacity |= (initialCapacity >>> 4);
134 initialCapacity |= (initialCapacity >>> 8);
135 initialCapacity |= (initialCapacity >>> 16);
138 if (initialCapacity < 0) // Too many elements, must back off
139 initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
141 elements = (E[]) new Object[initialCapacity];
145 * Double the capacity of this deque. Call only when full, i.e.,
146 * when head and tail have wrapped around to become equal.
148 private void doubleCapacity() {
151 int n = elements.length;
152 int r = n - p; // number of elements to the right of p
153 int newCapacity = n << 1;
155 throw new IllegalStateException("Sorry, deque too big");
156 Object[] a = new Object[newCapacity];
157 System.arraycopy(elements, p, a, 0, r);
158 System.arraycopy(elements, 0, a, r, p);
165 * Copies the elements from our element array into the specified array,
166 * in order (from first to last element in the deque). It is assumed
167 * that the array is large enough to hold all elements in the deque.
169 * @return its argument
171 private <T> T[] copyElements(T[] a) {
173 System.arraycopy(elements, head, a, 0, size());
174 } else if (head > tail) {
175 int headPortionLen = elements.length - head;
176 System.arraycopy(elements, head, a, 0, headPortionLen);
177 System.arraycopy(elements, 0, a, headPortionLen, tail);
183 * Constructs an empty array deque with an initial capacity
184 * sufficient to hold 16 elements.
186 public ArrayDeque() {
187 elements = (E[]) new Object[16];
191 * Constructs an empty array deque with an initial capacity
192 * sufficient to hold the specified number of elements.
194 * @param numElements lower bound on initial capacity of the deque
196 public ArrayDeque(int numElements) {
197 allocateElements(numElements);
201 * Constructs a deque containing the elements of the specified
202 * collection, in the order they are returned by the collection's
203 * iterator. (The first element returned by the collection's
204 * iterator becomes the first element, or <i>front</i> of the
207 * @param c the collection whose elements are to be placed into the deque
208 * @throws NullPointerException if the specified collection is null
210 public ArrayDeque(Collection<? extends E> c) {
211 allocateElements(c.size());
215 // The main insertion and extraction methods are addFirst,
216 // addLast, pollFirst, pollLast. The other methods are defined in
220 * Inserts the specified element at the front of this deque.
222 * @param e the element to add
223 * @throws NullPointerException if the specified element is null
225 public void addFirst(E e) {
227 throw new NullPointerException();
228 elements[head = (head - 1) & (elements.length - 1)] = e;
234 * Inserts the specified element at the end of this deque.
236 * <p>This method is equivalent to {@link #add}.
238 * @param e the element to add
239 * @throws NullPointerException if the specified element is null
241 public void addLast(E e) {
243 throw new NullPointerException();
245 if ( (tail = (tail + 1) & (elements.length - 1)) == head)
250 * Inserts the specified element at the front of this deque.
252 * @param e the element to add
253 * @return <tt>true</tt> (as specified by {@link Deque#offerFirst})
254 * @throws NullPointerException if the specified element is null
256 public boolean offerFirst(E e) {
262 * Inserts the specified element at the end of this deque.
264 * @param e the element to add
265 * @return <tt>true</tt> (as specified by {@link Deque#offerLast})
266 * @throws NullPointerException if the specified element is null
268 public boolean offerLast(E e) {
274 * @throws NoSuchElementException {@inheritDoc}
276 public E removeFirst() {
279 throw new NoSuchElementException();
284 * @throws NoSuchElementException {@inheritDoc}
286 public E removeLast() {
289 throw new NoSuchElementException();
293 public E pollFirst() {
295 E result = elements[h]; // Element is null if deque empty
298 elements[h] = null; // Must null out slot
299 head = (h + 1) & (elements.length - 1);
303 public E pollLast() {
304 int t = (tail - 1) & (elements.length - 1);
305 E result = elements[t];
314 * @throws NoSuchElementException {@inheritDoc}
316 public E getFirst() {
317 E x = elements[head];
319 throw new NoSuchElementException();
324 * @throws NoSuchElementException {@inheritDoc}
327 E x = elements[(tail - 1) & (elements.length - 1)];
329 throw new NoSuchElementException();
333 public E peekFirst() {
334 return elements[head]; // elements[head] is null if deque empty
337 public E peekLast() {
338 return elements[(tail - 1) & (elements.length - 1)];
342 * Removes the first occurrence of the specified element in this
343 * deque (when traversing the deque from head to tail).
344 * If the deque does not contain the element, it is unchanged.
345 * More formally, removes the first element <tt>e</tt> such that
346 * <tt>o.equals(e)</tt> (if such an element exists).
347 * Returns <tt>true</tt> if this deque contained the specified element
348 * (or equivalently, if this deque changed as a result of the call).
350 * @param o element to be removed from this deque, if present
351 * @return <tt>true</tt> if the deque contained the specified element
353 public boolean removeFirstOccurrence(Object o) {
356 int mask = elements.length - 1;
359 while ( (x = elements[i]) != null) {
370 * Removes the last occurrence of the specified element in this
371 * deque (when traversing the deque from head to tail).
372 * If the deque does not contain the element, it is unchanged.
373 * More formally, removes the last element <tt>e</tt> such that
374 * <tt>o.equals(e)</tt> (if such an element exists).
375 * Returns <tt>true</tt> if this deque contained the specified element
376 * (or equivalently, if this deque changed as a result of the call).
378 * @param o element to be removed from this deque, if present
379 * @return <tt>true</tt> if the deque contained the specified element
381 public boolean removeLastOccurrence(Object o) {
384 int mask = elements.length - 1;
385 int i = (tail - 1) & mask;
387 while ( (x = elements[i]) != null) {
397 // *** Queue methods ***
400 * Inserts the specified element at the end of this deque.
402 * <p>This method is equivalent to {@link #addLast}.
404 * @param e the element to add
405 * @return <tt>true</tt> (as specified by {@link Collection#add})
406 * @throws NullPointerException if the specified element is null
408 public boolean add(E e) {
414 * Inserts the specified element at the end of this deque.
416 * <p>This method is equivalent to {@link #offerLast}.
418 * @param e the element to add
419 * @return <tt>true</tt> (as specified by {@link Queue#offer})
420 * @throws NullPointerException if the specified element is null
422 public boolean offer(E e) {
427 * Retrieves and removes the head of the queue represented by this deque.
429 * This method differs from {@link #poll poll} only in that it throws an
430 * exception if this deque is empty.
432 * <p>This method is equivalent to {@link #removeFirst}.
434 * @return the head of the queue represented by this deque
435 * @throws NoSuchElementException {@inheritDoc}
438 return removeFirst();
442 * Retrieves and removes the head of the queue represented by this deque
443 * (in other words, the first element of this deque), or returns
444 * <tt>null</tt> if this deque is empty.
446 * <p>This method is equivalent to {@link #pollFirst}.
448 * @return the head of the queue represented by this deque, or
449 * <tt>null</tt> if this deque is empty
456 * Retrieves, but does not remove, the head of the queue represented by
457 * this deque. This method differs from {@link #peek peek} only in
458 * that it throws an exception if this deque is empty.
460 * <p>This method is equivalent to {@link #getFirst}.
462 * @return the head of the queue represented by this deque
463 * @throws NoSuchElementException {@inheritDoc}
470 * Retrieves, but does not remove, the head of the queue represented by
471 * this deque, or returns <tt>null</tt> if this deque is empty.
473 * <p>This method is equivalent to {@link #peekFirst}.
475 * @return the head of the queue represented by this deque, or
476 * <tt>null</tt> if this deque is empty
482 // *** Stack methods ***
485 * Pushes an element onto the stack represented by this deque. In other
486 * words, inserts the element at the front of this deque.
488 * <p>This method is equivalent to {@link #addFirst}.
490 * @param e the element to push
491 * @throws NullPointerException if the specified element is null
493 public void push(E e) {
498 * Pops an element from the stack represented by this deque. In other
499 * words, removes and returns the first element of this deque.
501 * <p>This method is equivalent to {@link #removeFirst()}.
503 * @return the element at the front of this deque (which is the top
504 * of the stack represented by this deque)
505 * @throws NoSuchElementException {@inheritDoc}
508 return removeFirst();
511 private void checkInvariants() {
512 assert elements[tail] == null;
513 assert head == tail ? elements[head] == null :
514 (elements[head] != null &&
515 elements[(tail - 1) & (elements.length - 1)] != null);
516 assert elements[(head - 1) & (elements.length - 1)] == null;
520 * Removes the element at the specified position in the elements array,
521 * adjusting head and tail as necessary. This can result in motion of
522 * elements backwards or forwards in the array.
524 * <p>This method is called delete rather than remove to emphasize
525 * that its semantics differ from those of {@link List#remove(int)}.
527 * @return true if elements moved backwards
529 private boolean delete(int i) {
531 final E[] elements = this.elements;
532 final int mask = elements.length - 1;
535 final int front = (i - h) & mask;
536 final int back = (t - i) & mask;
538 // Invariant: head <= i < tail mod circularity
539 if (front >= ((t - h) & mask))
540 throw new ConcurrentModificationException();
542 // Optimize for least element motion
545 System.arraycopy(elements, h, elements, h + 1, front);
546 } else { // Wrap around
547 System.arraycopy(elements, 0, elements, 1, i);
548 elements[0] = elements[mask];
549 System.arraycopy(elements, h, elements, h + 1, mask - h);
552 head = (h + 1) & mask;
555 if (i < t) { // Copy the null tail as well
556 System.arraycopy(elements, i + 1, elements, i, back);
558 } else { // Wrap around
559 System.arraycopy(elements, i + 1, elements, i, mask - i);
560 elements[mask] = elements[0];
561 System.arraycopy(elements, 1, elements, 0, t);
562 tail = (t - 1) & mask;
568 // *** Collection Methods ***
571 * Returns the number of elements in this deque.
573 * @return the number of elements in this deque
576 return (tail - head) & (elements.length - 1);
580 * Returns <tt>true</tt> if this deque contains no elements.
582 * @return <tt>true</tt> if this deque contains no elements
584 public boolean isEmpty() {
589 * Returns an iterator over the elements in this deque. The elements
590 * will be ordered from first (head) to last (tail). This is the same
591 * order that elements would be dequeued (via successive calls to
592 * {@link #remove} or popped (via successive calls to {@link #pop}).
594 * @return an iterator over the elements in this deque
596 public Iterator<E> iterator() {
597 return new DeqIterator();
600 public Iterator<E> descendingIterator() {
601 return new DescendingIterator();
604 private class DeqIterator implements Iterator<E> {
606 * Index of element to be returned by subsequent call to next.
608 private int cursor = head;
611 * Tail recorded at construction (also in remove), to stop
612 * iterator and also to check for comodification.
614 private int fence = tail;
617 * Index of element returned by most recent call to next.
618 * Reset to -1 if element is deleted by a call to remove.
620 private int lastRet = -1;
622 public boolean hasNext() {
623 return cursor != fence;
628 throw new NoSuchElementException();
629 E result = elements[cursor];
630 // This check doesn't catch all possible comodifications,
631 // but does catch the ones that corrupt traversal
632 if (tail != fence || result == null)
633 throw new ConcurrentModificationException();
635 cursor = (cursor + 1) & (elements.length - 1);
639 public void remove() {
641 throw new IllegalStateException();
642 if (delete(lastRet)) { // if left-shifted, undo increment in next()
643 cursor = (cursor - 1) & (elements.length - 1);
650 private class DescendingIterator implements Iterator<E> {
652 * This class is nearly a mirror-image of DeqIterator, using
653 * tail instead of head for initial cursor, and head instead of
656 private int cursor = tail;
657 private int fence = head;
658 private int lastRet = -1;
660 public boolean hasNext() {
661 return cursor != fence;
666 throw new NoSuchElementException();
667 cursor = (cursor - 1) & (elements.length - 1);
668 E result = elements[cursor];
669 if (head != fence || result == null)
670 throw new ConcurrentModificationException();
675 public void remove() {
677 throw new IllegalStateException();
678 if (!delete(lastRet)) {
679 cursor = (cursor + 1) & (elements.length - 1);
687 * Returns <tt>true</tt> if this deque contains the specified element.
688 * More formally, returns <tt>true</tt> if and only if this deque contains
689 * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
691 * @param o object to be checked for containment in this deque
692 * @return <tt>true</tt> if this deque contains the specified element
694 public boolean contains(Object o) {
697 int mask = elements.length - 1;
700 while ( (x = elements[i]) != null) {
709 * Removes a single instance of the specified element from this deque.
710 * If the deque does not contain the element, it is unchanged.
711 * More formally, removes the first element <tt>e</tt> such that
712 * <tt>o.equals(e)</tt> (if such an element exists).
713 * Returns <tt>true</tt> if this deque contained the specified element
714 * (or equivalently, if this deque changed as a result of the call).
716 * <p>This method is equivalent to {@link #removeFirstOccurrence}.
718 * @param o element to be removed from this deque, if present
719 * @return <tt>true</tt> if this deque contained the specified element
721 public boolean remove(Object o) {
722 return removeFirstOccurrence(o);
726 * Removes all of the elements from this deque.
727 * The deque will be empty after this call returns.
729 public void clear() {
732 if (h != t) { // clear all cells
735 int mask = elements.length - 1;
744 * Returns an array containing all of the elements in this deque
745 * in proper sequence (from first to last element).
747 * <p>The returned array will be "safe" in that no references to it are
748 * maintained by this deque. (In other words, this method must allocate
749 * a new array). The caller is thus free to modify the returned array.
751 * <p>This method acts as bridge between array-based and collection-based
754 * @return an array containing all of the elements in this deque
756 public Object[] toArray() {
757 return copyElements(new Object[size()]);
761 * Returns an array containing all of the elements in this deque in
762 * proper sequence (from first to last element); the runtime type of the
763 * returned array is that of the specified array. If the deque fits in
764 * the specified array, it is returned therein. Otherwise, a new array
765 * is allocated with the runtime type of the specified array and the
766 * size of this deque.
768 * <p>If this deque fits in the specified array with room to spare
769 * (i.e., the array has more elements than this deque), the element in
770 * the array immediately following the end of the deque is set to
773 * <p>Like the {@link #toArray()} method, this method acts as bridge between
774 * array-based and collection-based APIs. Further, this method allows
775 * precise control over the runtime type of the output array, and may,
776 * under certain circumstances, be used to save allocation costs.
778 * <p>Suppose <tt>x</tt> is a deque known to contain only strings.
779 * The following code can be used to dump the deque into a newly
780 * allocated array of <tt>String</tt>:
783 * String[] y = x.toArray(new String[0]);</pre>
785 * Note that <tt>toArray(new Object[0])</tt> is identical in function to
786 * <tt>toArray()</tt>.
788 * @param a the array into which the elements of the deque are to
789 * be stored, if it is big enough; otherwise, a new array of the
790 * same runtime type is allocated for this purpose
791 * @return an array containing all of the elements in this deque
792 * @throws ArrayStoreException if the runtime type of the specified array
793 * is not a supertype of the runtime type of every element in
795 * @throws NullPointerException if the specified array is null
797 public <T> T[] toArray(T[] a) {
800 a = (T[])java.lang.reflect.Array.newInstance(
801 a.getClass().getComponentType(), size);
808 // *** Object methods ***
811 * Returns a copy of this deque.
813 * @return a copy of this deque
815 public ArrayDeque<E> clone() {
817 ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
818 result.elements = Arrays.copyOf(elements, elements.length);
821 } catch (CloneNotSupportedException e) {
822 throw new AssertionError();
827 * Appease the serialization gods.
829 private static final long serialVersionUID = 2340985798034038923L;