1 /*
2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3  *
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.
9  *
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).
15  *
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.
19  *
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
22  * questions.
23  */
24 
25 /*
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
29  * file:
30  *
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/.
33  */
34 
35 package java.util;
36 
37 import java.io.Serializable;
38 import java.util.function.Consumer;
39 
40 // BEGIN android-note
41 // removed link to collections framework docs
42 // END android-note
43 
44 /**
45  * Resizable-array implementation of the {@link Deque} interface.  Array
46  * deques have no capacity restrictions; they grow as necessary to support
47  * usage.  They are not thread-safe; in the absence of external
48  * synchronization, they do not support concurrent access by multiple threads.
49  * Null elements are prohibited.  This class is likely to be faster than
50  * {@link Stack} when used as a stack, and faster than {@link LinkedList}
51  * when used as a queue.
52  *
53  * <p>Most {@code ArrayDeque} operations run in amortized constant time.
54  * Exceptions include
55  * {@link #remove(Object) remove},
56  * {@link #removeFirstOccurrence removeFirstOccurrence},
57  * {@link #removeLastOccurrence removeLastOccurrence},
58  * {@link #contains contains},
59  * {@link #iterator iterator.remove()},
60  * and the bulk operations, all of which run in linear time.
61  *
62  * <p>The iterators returned by this class's {@link #iterator() iterator}
63  * method are <em>fail-fast</em>: If the deque is modified at any time after
64  * the iterator is created, in any way except through the iterator's own
65  * {@code remove} method, the iterator will generally throw a {@link
66  * ConcurrentModificationException}.  Thus, in the face of concurrent
67  * modification, the iterator fails quickly and cleanly, rather than risking
68  * arbitrary, non-deterministic behavior at an undetermined time in the
69  * future.
70  *
71  * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
72  * as it is, generally speaking, impossible to make any hard guarantees in the
73  * presence of unsynchronized concurrent modification.  Fail-fast iterators
74  * throw {@code ConcurrentModificationException} on a best-effort basis.
75  * Therefore, it would be wrong to write a program that depended on this
76  * exception for its correctness: <i>the fail-fast behavior of iterators
77  * should be used only to detect bugs.</i>
78  *
79  * <p>This class and its iterator implement all of the
80  * <em>optional</em> methods of the {@link Collection} and {@link
81  * Iterator} interfaces.
82  *
83  * @author  Josh Bloch and Doug Lea
84  * @since   1.6
85  * @param <E> the type of elements held in this deque
86  */
87 public class ArrayDeque<E> extends AbstractCollection<E>
88                            implements Deque<E>, Cloneable, Serializable
89 {
90     /**
91      * The array in which the elements of the deque are stored.
92      * The capacity of the deque is the length of this array, which is
93      * always a power of two. The array is never allowed to become
94      * full, except transiently within an addX method where it is
95      * resized (see doubleCapacity) immediately upon becoming full,
96      * thus avoiding head and tail wrapping around to equal each
97      * other.  We also guarantee that all array cells not holding
98      * deque elements are always null.
99      */
100     transient Object[] elements; // non-private to simplify nested class access
101 
102     /**
103      * The index of the element at the head of the deque (which is the
104      * element that would be removed by remove() or pop()); or an
105      * arbitrary number equal to tail if the deque is empty.
106      */
107     transient int head;
108 
109     /**
110      * The index at which the next element would be added to the tail
111      * of the deque (via addLast(E), add(E), or push(E)).
112      */
113     transient int tail;
114 
115     /**
116      * The minimum capacity that we'll use for a newly created deque.
117      * Must be a power of 2.
118      */
119     private static final int MIN_INITIAL_CAPACITY = 8;
120 
121     // ******  Array allocation and resizing utilities ******
122 
123     /**
124      * Allocates empty array to hold the given number of elements.
125      *
126      * @param numElements  the number of elements to hold
127      */
allocateElements(int numElements)128     private void allocateElements(int numElements) {
129         int initialCapacity = MIN_INITIAL_CAPACITY;
130         // Find the best power of two to hold elements.
131         // Tests "<=" because arrays aren't kept full.
132         if (numElements >= initialCapacity) {
133             initialCapacity = numElements;
134             initialCapacity |= (initialCapacity >>>  1);
135             initialCapacity |= (initialCapacity >>>  2);
136             initialCapacity |= (initialCapacity >>>  4);
137             initialCapacity |= (initialCapacity >>>  8);
138             initialCapacity |= (initialCapacity >>> 16);
139             initialCapacity++;
140 
141             if (initialCapacity < 0)    // Too many elements, must back off
142                 initialCapacity >>>= 1; // Good luck allocating 2^30 elements
143         }
144         elements = new Object[initialCapacity];
145     }
146 
147     /**
148      * Doubles the capacity of this deque.  Call only when full, i.e.,
149      * when head and tail have wrapped around to become equal.
150      */
doubleCapacity()151     private void doubleCapacity() {
152         assert head == tail;
153         int p = head;
154         int n = elements.length;
155         int r = n - p; // number of elements to the right of p
156         int newCapacity = n << 1;
157         if (newCapacity < 0)
158             throw new IllegalStateException("Sorry, deque too big");
159         Object[] a = new Object[newCapacity];
160         System.arraycopy(elements, p, a, 0, r);
161         System.arraycopy(elements, 0, a, r, p);
162         // Android-added: Clear old array instance that's about to become eligible for GC.
163         // This ensures that array elements can be eligible for garbage collection even
164         // before the array itself is recognized as being eligible; the latter might
165         // take a while in some GC implementations, if the array instance is longer lived
166         // (its liveness rarely checked) than some of its contents.
167         Arrays.fill(elements, null);
168         elements = a;
169         head = 0;
170         tail = n;
171     }
172 
173     /**
174      * Constructs an empty array deque with an initial capacity
175      * sufficient to hold 16 elements.
176      */
ArrayDeque()177     public ArrayDeque() {
178         elements = new Object[16];
179     }
180 
181     /**
182      * Constructs an empty array deque with an initial capacity
183      * sufficient to hold the specified number of elements.
184      *
185      * @param numElements  lower bound on initial capacity of the deque
186      */
ArrayDeque(int numElements)187     public ArrayDeque(int numElements) {
188         allocateElements(numElements);
189     }
190 
191     /**
192      * Constructs a deque containing the elements of the specified
193      * collection, in the order they are returned by the collection's
194      * iterator.  (The first element returned by the collection's
195      * iterator becomes the first element, or <i>front</i> of the
196      * deque.)
197      *
198      * @param c the collection whose elements are to be placed into the deque
199      * @throws NullPointerException if the specified collection is null
200      */
ArrayDeque(Collection<? extends E> c)201     public ArrayDeque(Collection<? extends E> c) {
202         allocateElements(c.size());
203         addAll(c);
204     }
205 
206     // The main insertion and extraction methods are addFirst,
207     // addLast, pollFirst, pollLast. The other methods are defined in
208     // terms of these.
209 
210     /**
211      * Inserts the specified element at the front of this deque.
212      *
213      * @param e the element to add
214      * @throws NullPointerException if the specified element is null
215      */
addFirst(E e)216     public void addFirst(E e) {
217         if (e == null)
218             throw new NullPointerException();
219         elements[head = (head - 1) & (elements.length - 1)] = e;
220         if (head == tail)
221             doubleCapacity();
222     }
223 
224     /**
225      * Inserts the specified element at the end of this deque.
226      *
227      * <p>This method is equivalent to {@link #add}.
228      *
229      * @param e the element to add
230      * @throws NullPointerException if the specified element is null
231      */
addLast(E e)232     public void addLast(E e) {
233         if (e == null)
234             throw new NullPointerException();
235         elements[tail] = e;
236         if ( (tail = (tail + 1) & (elements.length - 1)) == head)
237             doubleCapacity();
238     }
239 
240     /**
241      * Inserts the specified element at the front of this deque.
242      *
243      * @param e the element to add
244      * @return {@code true} (as specified by {@link Deque#offerFirst})
245      * @throws NullPointerException if the specified element is null
246      */
offerFirst(E e)247     public boolean offerFirst(E e) {
248         addFirst(e);
249         return true;
250     }
251 
252     /**
253      * Inserts the specified element at the end of this deque.
254      *
255      * @param e the element to add
256      * @return {@code true} (as specified by {@link Deque#offerLast})
257      * @throws NullPointerException if the specified element is null
258      */
offerLast(E e)259     public boolean offerLast(E e) {
260         addLast(e);
261         return true;
262     }
263 
264     /**
265      * @throws NoSuchElementException {@inheritDoc}
266      */
removeFirst()267     public E removeFirst() {
268         E x = pollFirst();
269         if (x == null)
270             throw new NoSuchElementException();
271         return x;
272     }
273 
274     /**
275      * @throws NoSuchElementException {@inheritDoc}
276      */
removeLast()277     public E removeLast() {
278         E x = pollLast();
279         if (x == null)
280             throw new NoSuchElementException();
281         return x;
282     }
283 
pollFirst()284     public E pollFirst() {
285         final Object[] elements = this.elements;
286         final int h = head;
287         @SuppressWarnings("unchecked")
288         E result = (E) elements[h];
289         // Element is null if deque empty
290         if (result != null) {
291             elements[h] = null; // Must null out slot
292             head = (h + 1) & (elements.length - 1);
293         }
294         return result;
295     }
296 
pollLast()297     public E pollLast() {
298         final Object[] elements = this.elements;
299         final int t = (tail - 1) & (elements.length - 1);
300         @SuppressWarnings("unchecked")
301         E result = (E) elements[t];
302         if (result != null) {
303             elements[t] = null;
304             tail = t;
305         }
306         return result;
307     }
308 
309     /**
310      * @throws NoSuchElementException {@inheritDoc}
311      */
getFirst()312     public E getFirst() {
313         @SuppressWarnings("unchecked")
314         E result = (E) elements[head];
315         if (result == null)
316             throw new NoSuchElementException();
317         return result;
318     }
319 
320     /**
321      * @throws NoSuchElementException {@inheritDoc}
322      */
getLast()323     public E getLast() {
324         @SuppressWarnings("unchecked")
325         E result = (E) elements[(tail - 1) & (elements.length - 1)];
326         if (result == null)
327             throw new NoSuchElementException();
328         return result;
329     }
330 
331     @SuppressWarnings("unchecked")
peekFirst()332     public E peekFirst() {
333         // elements[head] is null if deque empty
334         return (E) elements[head];
335     }
336 
337     @SuppressWarnings("unchecked")
peekLast()338     public E peekLast() {
339         return (E) elements[(tail - 1) & (elements.length - 1)];
340     }
341 
342     /**
343      * Removes the first occurrence of the specified element in this
344      * deque (when traversing the deque from head to tail).
345      * If the deque does not contain the element, it is unchanged.
346      * More formally, removes the first element {@code e} such that
347      * {@code o.equals(e)} (if such an element exists).
348      * Returns {@code true} if this deque contained the specified element
349      * (or equivalently, if this deque changed as a result of the call).
350      *
351      * @param o element to be removed from this deque, if present
352      * @return {@code true} if the deque contained the specified element
353      */
removeFirstOccurrence(Object o)354     public boolean removeFirstOccurrence(Object o) {
355         if (o != null) {
356             int mask = elements.length - 1;
357             int i = head;
358             for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
359                 if (o.equals(x)) {
360                     delete(i);
361                     return true;
362                 }
363             }
364         }
365         return false;
366     }
367 
368     /**
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 {@code e} such that
373      * {@code o.equals(e)} (if such an element exists).
374      * Returns {@code true} if this deque contained the specified element
375      * (or equivalently, if this deque changed as a result of the call).
376      *
377      * @param o element to be removed from this deque, if present
378      * @return {@code true} if the deque contained the specified element
379      */
removeLastOccurrence(Object o)380     public boolean removeLastOccurrence(Object o) {
381         if (o != null) {
382             int mask = elements.length - 1;
383             int i = (tail - 1) & mask;
384             for (Object x; (x = elements[i]) != null; i = (i - 1) & mask) {
385                 if (o.equals(x)) {
386                     delete(i);
387                     return true;
388                 }
389             }
390         }
391         return false;
392     }
393 
394     // *** Queue methods ***
395 
396     /**
397      * Inserts the specified element at the end of this deque.
398      *
399      * <p>This method is equivalent to {@link #addLast}.
400      *
401      * @param e the element to add
402      * @return {@code true} (as specified by {@link Collection#add})
403      * @throws NullPointerException if the specified element is null
404      */
add(E e)405     public boolean add(E e) {
406         addLast(e);
407         return true;
408     }
409 
410     /**
411      * Inserts the specified element at the end of this deque.
412      *
413      * <p>This method is equivalent to {@link #offerLast}.
414      *
415      * @param e the element to add
416      * @return {@code true} (as specified by {@link Queue#offer})
417      * @throws NullPointerException if the specified element is null
418      */
offer(E e)419     public boolean offer(E e) {
420         return offerLast(e);
421     }
422 
423     /**
424      * Retrieves and removes the head of the queue represented by this deque.
425      *
426      * This method differs from {@link #poll poll} only in that it throws an
427      * exception if this deque is empty.
428      *
429      * <p>This method is equivalent to {@link #removeFirst}.
430      *
431      * @return the head of the queue represented by this deque
432      * @throws NoSuchElementException {@inheritDoc}
433      */
remove()434     public E remove() {
435         return removeFirst();
436     }
437 
438     /**
439      * Retrieves and removes the head of the queue represented by this deque
440      * (in other words, the first element of this deque), or returns
441      * {@code null} if this deque is empty.
442      *
443      * <p>This method is equivalent to {@link #pollFirst}.
444      *
445      * @return the head of the queue represented by this deque, or
446      *         {@code null} if this deque is empty
447      */
poll()448     public E poll() {
449         return pollFirst();
450     }
451 
452     /**
453      * Retrieves, but does not remove, the head of the queue represented by
454      * this deque.  This method differs from {@link #peek peek} only in
455      * that it throws an exception if this deque is empty.
456      *
457      * <p>This method is equivalent to {@link #getFirst}.
458      *
459      * @return the head of the queue represented by this deque
460      * @throws NoSuchElementException {@inheritDoc}
461      */
element()462     public E element() {
463         return getFirst();
464     }
465 
466     /**
467      * Retrieves, but does not remove, the head of the queue represented by
468      * this deque, or returns {@code null} if this deque is empty.
469      *
470      * <p>This method is equivalent to {@link #peekFirst}.
471      *
472      * @return the head of the queue represented by this deque, or
473      *         {@code null} if this deque is empty
474      */
peek()475     public E peek() {
476         return peekFirst();
477     }
478 
479     // *** Stack methods ***
480 
481     /**
482      * Pushes an element onto the stack represented by this deque.  In other
483      * words, inserts the element at the front of this deque.
484      *
485      * <p>This method is equivalent to {@link #addFirst}.
486      *
487      * @param e the element to push
488      * @throws NullPointerException if the specified element is null
489      */
push(E e)490     public void push(E e) {
491         addFirst(e);
492     }
493 
494     /**
495      * Pops an element from the stack represented by this deque.  In other
496      * words, removes and returns the first element of this deque.
497      *
498      * <p>This method is equivalent to {@link #removeFirst()}.
499      *
500      * @return the element at the front of this deque (which is the top
501      *         of the stack represented by this deque)
502      * @throws NoSuchElementException {@inheritDoc}
503      */
pop()504     public E pop() {
505         return removeFirst();
506     }
507 
checkInvariants()508     private void checkInvariants() {
509         assert elements[tail] == null;
510         assert head == tail ? elements[head] == null :
511             (elements[head] != null &&
512              elements[(tail - 1) & (elements.length - 1)] != null);
513         assert elements[(head - 1) & (elements.length - 1)] == null;
514     }
515 
516     /**
517      * Removes the element at the specified position in the elements array,
518      * adjusting head and tail as necessary.  This can result in motion of
519      * elements backwards or forwards in the array.
520      *
521      * <p>This method is called delete rather than remove to emphasize
522      * that its semantics differ from those of {@link List#remove(int)}.
523      *
524      * @return true if elements moved backwards
525      */
delete(int i)526     boolean delete(int i) {
527         checkInvariants();
528         final Object[] elements = this.elements;
529         final int mask = elements.length - 1;
530         final int h = head;
531         final int t = tail;
532         final int front = (i - h) & mask;
533         final int back  = (t - i) & mask;
534 
535         // Invariant: head <= i < tail mod circularity
536         if (front >= ((t - h) & mask))
537             throw new ConcurrentModificationException();
538 
539         // Optimize for least element motion
540         if (front < back) {
541             if (h <= i) {
542                 System.arraycopy(elements, h, elements, h + 1, front);
543             } else { // Wrap around
544                 System.arraycopy(elements, 0, elements, 1, i);
545                 elements[0] = elements[mask];
546                 System.arraycopy(elements, h, elements, h + 1, mask - h);
547             }
548             elements[h] = null;
549             head = (h + 1) & mask;
550             return false;
551         } else {
552             if (i < t) { // Copy the null tail as well
553                 System.arraycopy(elements, i + 1, elements, i, back);
554                 tail = t - 1;
555             } else { // Wrap around
556                 System.arraycopy(elements, i + 1, elements, i, mask - i);
557                 elements[mask] = elements[0];
558                 System.arraycopy(elements, 1, elements, 0, t);
559                 tail = (t - 1) & mask;
560             }
561             return true;
562         }
563     }
564 
565     // *** Collection Methods ***
566 
567     /**
568      * Returns the number of elements in this deque.
569      *
570      * @return the number of elements in this deque
571      */
size()572     public int size() {
573         return (tail - head) & (elements.length - 1);
574     }
575 
576     /**
577      * Returns {@code true} if this deque contains no elements.
578      *
579      * @return {@code true} if this deque contains no elements
580      */
isEmpty()581     public boolean isEmpty() {
582         return head == tail;
583     }
584 
585     /**
586      * Returns an iterator over the elements in this deque.  The elements
587      * will be ordered from first (head) to last (tail).  This is the same
588      * order that elements would be dequeued (via successive calls to
589      * {@link #remove} or popped (via successive calls to {@link #pop}).
590      *
591      * @return an iterator over the elements in this deque
592      */
iterator()593     public Iterator<E> iterator() {
594         return new DeqIterator();
595     }
596 
descendingIterator()597     public Iterator<E> descendingIterator() {
598         return new DescendingIterator();
599     }
600 
601     private class DeqIterator implements Iterator<E> {
602         /**
603          * Index of element to be returned by subsequent call to next.
604          */
605         private int cursor = head;
606 
607         /**
608          * Tail recorded at construction (also in remove), to stop
609          * iterator and also to check for comodification.
610          */
611         private int fence = tail;
612 
613         /**
614          * Index of element returned by most recent call to next.
615          * Reset to -1 if element is deleted by a call to remove.
616          */
617         private int lastRet = -1;
618 
hasNext()619         public boolean hasNext() {
620             return cursor != fence;
621         }
622 
next()623         public E next() {
624             if (cursor == fence)
625                 throw new NoSuchElementException();
626             @SuppressWarnings("unchecked")
627             E result = (E) elements[cursor];
628             // This check doesn't catch all possible comodifications,
629             // but does catch the ones that corrupt traversal
630             if (tail != fence || result == null)
631                 throw new ConcurrentModificationException();
632             lastRet = cursor;
633             cursor = (cursor + 1) & (elements.length - 1);
634             return result;
635         }
636 
remove()637         public void remove() {
638             if (lastRet < 0)
639                 throw new IllegalStateException();
640             if (delete(lastRet)) { // if left-shifted, undo increment in next()
641                 cursor = (cursor - 1) & (elements.length - 1);
642                 fence = tail;
643             }
644             lastRet = -1;
645         }
646 
647         @Override
forEachRemaining(Consumer<? super E> action)648         public void forEachRemaining(Consumer<? super E> action) {
649             Objects.requireNonNull(action);
650             Object[] a = elements;
651             int m = a.length - 1, f = fence, i = cursor;
652             cursor = f;
653             while (i != f) {
654                 @SuppressWarnings("unchecked") E e = (E)a[i];
655                 i = (i + 1) & m;
656                 // Android-note: This uses a different heuristic for detecting
657                 // concurrent modification exceptions than next(). As such, this is a less
658                 // precise test.
659                 if (e == null)
660                     throw new ConcurrentModificationException();
661                 action.accept(e);
662             }
663         }
664     }
665 
666     /**
667      * This class is nearly a mirror-image of DeqIterator, using tail
668      * instead of head for initial cursor, and head instead of tail
669      * for fence.
670      */
671     private class DescendingIterator implements Iterator<E> {
672         private int cursor = tail;
673         private int fence = head;
674         private int lastRet = -1;
675 
hasNext()676         public boolean hasNext() {
677             return cursor != fence;
678         }
679 
next()680         public E next() {
681             if (cursor == fence)
682                 throw new NoSuchElementException();
683             cursor = (cursor - 1) & (elements.length - 1);
684             @SuppressWarnings("unchecked")
685             E result = (E) elements[cursor];
686             if (head != fence || result == null)
687                 throw new ConcurrentModificationException();
688             lastRet = cursor;
689             return result;
690         }
691 
remove()692         public void remove() {
693             if (lastRet < 0)
694                 throw new IllegalStateException();
695             if (!delete(lastRet)) {
696                 cursor = (cursor + 1) & (elements.length - 1);
697                 fence = head;
698             }
699             lastRet = -1;
700         }
701     }
702 
703     /**
704      * Returns {@code true} if this deque contains the specified element.
705      * More formally, returns {@code true} if and only if this deque contains
706      * at least one element {@code e} such that {@code o.equals(e)}.
707      *
708      * @param o object to be checked for containment in this deque
709      * @return {@code true} if this deque contains the specified element
710      */
contains(Object o)711     public boolean contains(Object o) {
712         if (o != null) {
713             int mask = elements.length - 1;
714             int i = head;
715             for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
716                 if (o.equals(x))
717                     return true;
718             }
719         }
720         return false;
721     }
722 
723     /**
724      * Removes a single instance of the specified element from this deque.
725      * If the deque does not contain the element, it is unchanged.
726      * More formally, removes the first element {@code e} such that
727      * {@code o.equals(e)} (if such an element exists).
728      * Returns {@code true} if this deque contained the specified element
729      * (or equivalently, if this deque changed as a result of the call).
730      *
731      * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
732      *
733      * @param o element to be removed from this deque, if present
734      * @return {@code true} if this deque contained the specified element
735      */
remove(Object o)736     public boolean remove(Object o) {
737         return removeFirstOccurrence(o);
738     }
739 
740     /**
741      * Removes all of the elements from this deque.
742      * The deque will be empty after this call returns.
743      */
clear()744     public void clear() {
745         int h = head;
746         int t = tail;
747         if (h != t) { // clear all cells
748             head = tail = 0;
749             int i = h;
750             int mask = elements.length - 1;
751             do {
752                 elements[i] = null;
753                 i = (i + 1) & mask;
754             } while (i != t);
755         }
756     }
757 
758     /**
759      * Returns an array containing all of the elements in this deque
760      * in proper sequence (from first to last element).
761      *
762      * <p>The returned array will be "safe" in that no references to it are
763      * maintained by this deque.  (In other words, this method must allocate
764      * a new array).  The caller is thus free to modify the returned array.
765      *
766      * <p>This method acts as bridge between array-based and collection-based
767      * APIs.
768      *
769      * @return an array containing all of the elements in this deque
770      */
toArray()771     public Object[] toArray() {
772         final int head = this.head;
773         final int tail = this.tail;
774         boolean wrap = (tail < head);
775         int end = wrap ? tail + elements.length : tail;
776         Object[] a = Arrays.copyOfRange(elements, head, end);
777         if (wrap)
778             System.arraycopy(elements, 0, a, elements.length - head, tail);
779         return a;
780     }
781 
782     /**
783      * Returns an array containing all of the elements in this deque in
784      * proper sequence (from first to last element); the runtime type of the
785      * returned array is that of the specified array.  If the deque fits in
786      * the specified array, it is returned therein.  Otherwise, a new array
787      * is allocated with the runtime type of the specified array and the
788      * size of this deque.
789      *
790      * <p>If this deque fits in the specified array with room to spare
791      * (i.e., the array has more elements than this deque), the element in
792      * the array immediately following the end of the deque is set to
793      * {@code null}.
794      *
795      * <p>Like the {@link #toArray()} method, this method acts as bridge between
796      * array-based and collection-based APIs.  Further, this method allows
797      * precise control over the runtime type of the output array, and may,
798      * under certain circumstances, be used to save allocation costs.
799      *
800      * <p>Suppose {@code x} is a deque known to contain only strings.
801      * The following code can be used to dump the deque into a newly
802      * allocated array of {@code String}:
803      *
804      * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
805      *
806      * Note that {@code toArray(new Object[0])} is identical in function to
807      * {@code toArray()}.
808      *
809      * @param a the array into which the elements of the deque are to
810      *          be stored, if it is big enough; otherwise, a new array of the
811      *          same runtime type is allocated for this purpose
812      * @return an array containing all of the elements in this deque
813      * @throws ArrayStoreException if the runtime type of the specified array
814      *         is not a supertype of the runtime type of every element in
815      *         this deque
816      * @throws NullPointerException if the specified array is null
817      */
818     @SuppressWarnings("unchecked")
toArray(T[] a)819     public <T> T[] toArray(T[] a) {
820         final int head = this.head;
821         final int tail = this.tail;
822         boolean wrap = (tail < head);
823         int size = (tail - head) + (wrap ? elements.length : 0);
824         int firstLeg = size - (wrap ? tail : 0);
825         int len = a.length;
826         if (size > len) {
827             a = (T[]) Arrays.copyOfRange(elements, head, head + size,
828                                          a.getClass());
829         } else {
830             System.arraycopy(elements, head, a, 0, firstLeg);
831             if (size < len)
832                 a[size] = null;
833         }
834         if (wrap)
835             System.arraycopy(elements, 0, a, firstLeg, tail);
836         return a;
837     }
838 
839     // *** Object methods ***
840 
841     /**
842      * Returns a copy of this deque.
843      *
844      * @return a copy of this deque
845      */
clone()846     public ArrayDeque<E> clone() {
847         try {
848             @SuppressWarnings("unchecked")
849             ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
850             result.elements = Arrays.copyOf(elements, elements.length);
851             return result;
852         } catch (CloneNotSupportedException e) {
853             throw new AssertionError();
854         }
855     }
856 
857     private static final long serialVersionUID = 2340985798034038923L;
858 
859     /**
860      * Saves this deque to a stream (that is, serializes it).
861      *
862      * @param s the stream
863      * @throws java.io.IOException if an I/O error occurs
864      * @serialData The current size ({@code int}) of the deque,
865      * followed by all of its elements (each an object reference) in
866      * first-to-last order.
867      */
writeObject(java.io.ObjectOutputStream s)868     private void writeObject(java.io.ObjectOutputStream s)
869             throws java.io.IOException {
870         s.defaultWriteObject();
871 
872         // Write out size
873         s.writeInt(size());
874 
875         // Write out elements in order.
876         int mask = elements.length - 1;
877         for (int i = head; i != tail; i = (i + 1) & mask)
878             s.writeObject(elements[i]);
879     }
880 
881     /**
882      * Reconstitutes this deque from a stream (that is, deserializes it).
883      * @param s the stream
884      * @throws ClassNotFoundException if the class of a serialized object
885      *         could not be found
886      * @throws java.io.IOException if an I/O error occurs
887      */
readObject(java.io.ObjectInputStream s)888     private void readObject(java.io.ObjectInputStream s)
889             throws java.io.IOException, ClassNotFoundException {
890         s.defaultReadObject();
891 
892         // Read in size and allocate array
893         int size = s.readInt();
894         allocateElements(size);
895         head = 0;
896         tail = size;
897 
898         // Read in all elements in the proper order.
899         for (int i = 0; i < size; i++)
900             elements[i] = s.readObject();
901     }
902 
903     /**
904      * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
905      * and <em>fail-fast</em> {@link Spliterator} over the elements in this
906      * deque.
907      *
908      * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
909      * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
910      * {@link Spliterator#NONNULL}.  Overriding implementations should document
911      * the reporting of additional characteristic values.
912      *
913      * @return a {@code Spliterator} over the elements in this deque
914      * @since 1.8
915      */
spliterator()916     public Spliterator<E> spliterator() {
917         return new DeqSpliterator<>(this, -1, -1);
918     }
919 
920     static final class DeqSpliterator<E> implements Spliterator<E> {
921         private final ArrayDeque<E> deq;
922         private int fence;  // -1 until first use
923         private int index;  // current index, modified on traverse/split
924 
925         /** Creates new spliterator covering the given array and range. */
DeqSpliterator(ArrayDeque<E> deq, int origin, int fence)926         DeqSpliterator(ArrayDeque<E> deq, int origin, int fence) {
927             this.deq = deq;
928             this.index = origin;
929             this.fence = fence;
930         }
931 
getFence()932         private int getFence() { // force initialization
933             int t;
934             if ((t = fence) < 0) {
935                 t = fence = deq.tail;
936                 index = deq.head;
937             }
938             return t;
939         }
940 
trySplit()941         public DeqSpliterator<E> trySplit() {
942             int t = getFence(), h = index, n = deq.elements.length;
943             if (h != t && ((h + 1) & (n - 1)) != t) {
944                 if (h > t)
945                     t += n;
946                 int m = ((h + t) >>> 1) & (n - 1);
947                 return new DeqSpliterator<E>(deq, h, index = m);
948             }
949             return null;
950         }
951 
forEachRemaining(Consumer<? super E> consumer)952         public void forEachRemaining(Consumer<? super E> consumer) {
953             if (consumer == null)
954                 throw new NullPointerException();
955             Object[] a = deq.elements;
956             int m = a.length - 1, f = getFence(), i = index;
957             index = f;
958             while (i != f) {
959                 @SuppressWarnings("unchecked") E e = (E)a[i];
960                 i = (i + 1) & m;
961                 if (e == null)
962                     throw new ConcurrentModificationException();
963                 consumer.accept(e);
964             }
965         }
966 
tryAdvance(Consumer<? super E> consumer)967         public boolean tryAdvance(Consumer<? super E> consumer) {
968             if (consumer == null)
969                 throw new NullPointerException();
970             Object[] a = deq.elements;
971             int m = a.length - 1, f = getFence(), i = index;
972             if (i != f) {
973                 @SuppressWarnings("unchecked") E e = (E)a[i];
974                 index = (i + 1) & m;
975                 if (e == null)
976                     throw new ConcurrentModificationException();
977                 consumer.accept(e);
978                 return true;
979             }
980             return false;
981         }
982 
estimateSize()983         public long estimateSize() {
984             int n = getFence() - index;
985             if (n < 0)
986                 n += deq.elements.length;
987             return (long) n;
988         }
989 
990         @Override
characteristics()991         public int characteristics() {
992             return Spliterator.ORDERED | Spliterator.SIZED |
993                 Spliterator.NONNULL | Spliterator.SUBSIZED;
994         }
995     }
996 
997 }
998