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         elements = a;
163         head = 0;
164         tail = n;
165     }
166 
167     /**
168      * Constructs an empty array deque with an initial capacity
169      * sufficient to hold 16 elements.
170      */
ArrayDeque()171     public ArrayDeque() {
172         elements = new Object[16];
173     }
174 
175     /**
176      * Constructs an empty array deque with an initial capacity
177      * sufficient to hold the specified number of elements.
178      *
179      * @param numElements  lower bound on initial capacity of the deque
180      */
ArrayDeque(int numElements)181     public ArrayDeque(int numElements) {
182         allocateElements(numElements);
183     }
184 
185     /**
186      * Constructs a deque containing the elements of the specified
187      * collection, in the order they are returned by the collection's
188      * iterator.  (The first element returned by the collection's
189      * iterator becomes the first element, or <i>front</i> of the
190      * deque.)
191      *
192      * @param c the collection whose elements are to be placed into the deque
193      * @throws NullPointerException if the specified collection is null
194      */
ArrayDeque(Collection<? extends E> c)195     public ArrayDeque(Collection<? extends E> c) {
196         allocateElements(c.size());
197         addAll(c);
198     }
199 
200     // The main insertion and extraction methods are addFirst,
201     // addLast, pollFirst, pollLast. The other methods are defined in
202     // terms of these.
203 
204     /**
205      * Inserts the specified element at the front of this deque.
206      *
207      * @param e the element to add
208      * @throws NullPointerException if the specified element is null
209      */
addFirst(E e)210     public void addFirst(E e) {
211         if (e == null)
212             throw new NullPointerException();
213         elements[head = (head - 1) & (elements.length - 1)] = e;
214         if (head == tail)
215             doubleCapacity();
216     }
217 
218     /**
219      * Inserts the specified element at the end of this deque.
220      *
221      * <p>This method is equivalent to {@link #add}.
222      *
223      * @param e the element to add
224      * @throws NullPointerException if the specified element is null
225      */
addLast(E e)226     public void addLast(E e) {
227         if (e == null)
228             throw new NullPointerException();
229         elements[tail] = e;
230         if ( (tail = (tail + 1) & (elements.length - 1)) == head)
231             doubleCapacity();
232     }
233 
234     /**
235      * Inserts the specified element at the front of this deque.
236      *
237      * @param e the element to add
238      * @return {@code true} (as specified by {@link Deque#offerFirst})
239      * @throws NullPointerException if the specified element is null
240      */
offerFirst(E e)241     public boolean offerFirst(E e) {
242         addFirst(e);
243         return true;
244     }
245 
246     /**
247      * Inserts the specified element at the end of this deque.
248      *
249      * @param e the element to add
250      * @return {@code true} (as specified by {@link Deque#offerLast})
251      * @throws NullPointerException if the specified element is null
252      */
offerLast(E e)253     public boolean offerLast(E e) {
254         addLast(e);
255         return true;
256     }
257 
258     /**
259      * @throws NoSuchElementException {@inheritDoc}
260      */
removeFirst()261     public E removeFirst() {
262         E x = pollFirst();
263         if (x == null)
264             throw new NoSuchElementException();
265         return x;
266     }
267 
268     /**
269      * @throws NoSuchElementException {@inheritDoc}
270      */
removeLast()271     public E removeLast() {
272         E x = pollLast();
273         if (x == null)
274             throw new NoSuchElementException();
275         return x;
276     }
277 
pollFirst()278     public E pollFirst() {
279         final Object[] elements = this.elements;
280         final int h = head;
281         @SuppressWarnings("unchecked")
282         E result = (E) elements[h];
283         // Element is null if deque empty
284         if (result != null) {
285             elements[h] = null; // Must null out slot
286             head = (h + 1) & (elements.length - 1);
287         }
288         return result;
289     }
290 
pollLast()291     public E pollLast() {
292         final Object[] elements = this.elements;
293         final int t = (tail - 1) & (elements.length - 1);
294         @SuppressWarnings("unchecked")
295         E result = (E) elements[t];
296         if (result != null) {
297             elements[t] = null;
298             tail = t;
299         }
300         return result;
301     }
302 
303     /**
304      * @throws NoSuchElementException {@inheritDoc}
305      */
getFirst()306     public E getFirst() {
307         @SuppressWarnings("unchecked")
308         E result = (E) elements[head];
309         if (result == null)
310             throw new NoSuchElementException();
311         return result;
312     }
313 
314     /**
315      * @throws NoSuchElementException {@inheritDoc}
316      */
getLast()317     public E getLast() {
318         @SuppressWarnings("unchecked")
319         E result = (E) elements[(tail - 1) & (elements.length - 1)];
320         if (result == null)
321             throw new NoSuchElementException();
322         return result;
323     }
324 
325     @SuppressWarnings("unchecked")
peekFirst()326     public E peekFirst() {
327         // elements[head] is null if deque empty
328         return (E) elements[head];
329     }
330 
331     @SuppressWarnings("unchecked")
peekLast()332     public E peekLast() {
333         return (E) elements[(tail - 1) & (elements.length - 1)];
334     }
335 
336     /**
337      * Removes the first occurrence of the specified element in this
338      * deque (when traversing the deque from head to tail).
339      * If the deque does not contain the element, it is unchanged.
340      * More formally, removes the first element {@code e} such that
341      * {@code o.equals(e)} (if such an element exists).
342      * Returns {@code true} if this deque contained the specified element
343      * (or equivalently, if this deque changed as a result of the call).
344      *
345      * @param o element to be removed from this deque, if present
346      * @return {@code true} if the deque contained the specified element
347      */
removeFirstOccurrence(Object o)348     public boolean removeFirstOccurrence(Object o) {
349         if (o != null) {
350             int mask = elements.length - 1;
351             int i = head;
352             for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
353                 if (o.equals(x)) {
354                     delete(i);
355                     return true;
356                 }
357             }
358         }
359         return false;
360     }
361 
362     /**
363      * Removes the last occurrence of the specified element in this
364      * deque (when traversing the deque from head to tail).
365      * If the deque does not contain the element, it is unchanged.
366      * More formally, removes the last element {@code e} such that
367      * {@code o.equals(e)} (if such an element exists).
368      * Returns {@code true} if this deque contained the specified element
369      * (or equivalently, if this deque changed as a result of the call).
370      *
371      * @param o element to be removed from this deque, if present
372      * @return {@code true} if the deque contained the specified element
373      */
removeLastOccurrence(Object o)374     public boolean removeLastOccurrence(Object o) {
375         if (o != null) {
376             int mask = elements.length - 1;
377             int i = (tail - 1) & mask;
378             for (Object x; (x = elements[i]) != null; i = (i - 1) & mask) {
379                 if (o.equals(x)) {
380                     delete(i);
381                     return true;
382                 }
383             }
384         }
385         return false;
386     }
387 
388     // *** Queue methods ***
389 
390     /**
391      * Inserts the specified element at the end of this deque.
392      *
393      * <p>This method is equivalent to {@link #addLast}.
394      *
395      * @param e the element to add
396      * @return {@code true} (as specified by {@link Collection#add})
397      * @throws NullPointerException if the specified element is null
398      */
add(E e)399     public boolean add(E e) {
400         addLast(e);
401         return true;
402     }
403 
404     /**
405      * Inserts the specified element at the end of this deque.
406      *
407      * <p>This method is equivalent to {@link #offerLast}.
408      *
409      * @param e the element to add
410      * @return {@code true} (as specified by {@link Queue#offer})
411      * @throws NullPointerException if the specified element is null
412      */
offer(E e)413     public boolean offer(E e) {
414         return offerLast(e);
415     }
416 
417     /**
418      * Retrieves and removes the head of the queue represented by this deque.
419      *
420      * This method differs from {@link #poll poll} only in that it throws an
421      * exception if this deque is empty.
422      *
423      * <p>This method is equivalent to {@link #removeFirst}.
424      *
425      * @return the head of the queue represented by this deque
426      * @throws NoSuchElementException {@inheritDoc}
427      */
remove()428     public E remove() {
429         return removeFirst();
430     }
431 
432     /**
433      * Retrieves and removes the head of the queue represented by this deque
434      * (in other words, the first element of this deque), or returns
435      * {@code null} if this deque is empty.
436      *
437      * <p>This method is equivalent to {@link #pollFirst}.
438      *
439      * @return the head of the queue represented by this deque, or
440      *         {@code null} if this deque is empty
441      */
poll()442     public E poll() {
443         return pollFirst();
444     }
445 
446     /**
447      * Retrieves, but does not remove, the head of the queue represented by
448      * this deque.  This method differs from {@link #peek peek} only in
449      * that it throws an exception if this deque is empty.
450      *
451      * <p>This method is equivalent to {@link #getFirst}.
452      *
453      * @return the head of the queue represented by this deque
454      * @throws NoSuchElementException {@inheritDoc}
455      */
element()456     public E element() {
457         return getFirst();
458     }
459 
460     /**
461      * Retrieves, but does not remove, the head of the queue represented by
462      * this deque, or returns {@code null} if this deque is empty.
463      *
464      * <p>This method is equivalent to {@link #peekFirst}.
465      *
466      * @return the head of the queue represented by this deque, or
467      *         {@code null} if this deque is empty
468      */
peek()469     public E peek() {
470         return peekFirst();
471     }
472 
473     // *** Stack methods ***
474 
475     /**
476      * Pushes an element onto the stack represented by this deque.  In other
477      * words, inserts the element at the front of this deque.
478      *
479      * <p>This method is equivalent to {@link #addFirst}.
480      *
481      * @param e the element to push
482      * @throws NullPointerException if the specified element is null
483      */
push(E e)484     public void push(E e) {
485         addFirst(e);
486     }
487 
488     /**
489      * Pops an element from the stack represented by this deque.  In other
490      * words, removes and returns the first element of this deque.
491      *
492      * <p>This method is equivalent to {@link #removeFirst()}.
493      *
494      * @return the element at the front of this deque (which is the top
495      *         of the stack represented by this deque)
496      * @throws NoSuchElementException {@inheritDoc}
497      */
pop()498     public E pop() {
499         return removeFirst();
500     }
501 
checkInvariants()502     private void checkInvariants() {
503         assert elements[tail] == null;
504         assert head == tail ? elements[head] == null :
505             (elements[head] != null &&
506              elements[(tail - 1) & (elements.length - 1)] != null);
507         assert elements[(head - 1) & (elements.length - 1)] == null;
508     }
509 
510     /**
511      * Removes the element at the specified position in the elements array,
512      * adjusting head and tail as necessary.  This can result in motion of
513      * elements backwards or forwards in the array.
514      *
515      * <p>This method is called delete rather than remove to emphasize
516      * that its semantics differ from those of {@link List#remove(int)}.
517      *
518      * @return true if elements moved backwards
519      */
delete(int i)520     boolean delete(int i) {
521         checkInvariants();
522         final Object[] elements = this.elements;
523         final int mask = elements.length - 1;
524         final int h = head;
525         final int t = tail;
526         final int front = (i - h) & mask;
527         final int back  = (t - i) & mask;
528 
529         // Invariant: head <= i < tail mod circularity
530         if (front >= ((t - h) & mask))
531             throw new ConcurrentModificationException();
532 
533         // Optimize for least element motion
534         if (front < back) {
535             if (h <= i) {
536                 System.arraycopy(elements, h, elements, h + 1, front);
537             } else { // Wrap around
538                 System.arraycopy(elements, 0, elements, 1, i);
539                 elements[0] = elements[mask];
540                 System.arraycopy(elements, h, elements, h + 1, mask - h);
541             }
542             elements[h] = null;
543             head = (h + 1) & mask;
544             return false;
545         } else {
546             if (i < t) { // Copy the null tail as well
547                 System.arraycopy(elements, i + 1, elements, i, back);
548                 tail = t - 1;
549             } else { // Wrap around
550                 System.arraycopy(elements, i + 1, elements, i, mask - i);
551                 elements[mask] = elements[0];
552                 System.arraycopy(elements, 1, elements, 0, t);
553                 tail = (t - 1) & mask;
554             }
555             return true;
556         }
557     }
558 
559     // *** Collection Methods ***
560 
561     /**
562      * Returns the number of elements in this deque.
563      *
564      * @return the number of elements in this deque
565      */
size()566     public int size() {
567         return (tail - head) & (elements.length - 1);
568     }
569 
570     /**
571      * Returns {@code true} if this deque contains no elements.
572      *
573      * @return {@code true} if this deque contains no elements
574      */
isEmpty()575     public boolean isEmpty() {
576         return head == tail;
577     }
578 
579     /**
580      * Returns an iterator over the elements in this deque.  The elements
581      * will be ordered from first (head) to last (tail).  This is the same
582      * order that elements would be dequeued (via successive calls to
583      * {@link #remove} or popped (via successive calls to {@link #pop}).
584      *
585      * @return an iterator over the elements in this deque
586      */
iterator()587     public Iterator<E> iterator() {
588         return new DeqIterator();
589     }
590 
descendingIterator()591     public Iterator<E> descendingIterator() {
592         return new DescendingIterator();
593     }
594 
595     private class DeqIterator implements Iterator<E> {
596         /**
597          * Index of element to be returned by subsequent call to next.
598          */
599         private int cursor = head;
600 
601         /**
602          * Tail recorded at construction (also in remove), to stop
603          * iterator and also to check for comodification.
604          */
605         private int fence = tail;
606 
607         /**
608          * Index of element returned by most recent call to next.
609          * Reset to -1 if element is deleted by a call to remove.
610          */
611         private int lastRet = -1;
612 
hasNext()613         public boolean hasNext() {
614             return cursor != fence;
615         }
616 
next()617         public E next() {
618             if (cursor == fence)
619                 throw new NoSuchElementException();
620             @SuppressWarnings("unchecked")
621             E result = (E) elements[cursor];
622             // This check doesn't catch all possible comodifications,
623             // but does catch the ones that corrupt traversal
624             if (tail != fence || result == null)
625                 throw new ConcurrentModificationException();
626             lastRet = cursor;
627             cursor = (cursor + 1) & (elements.length - 1);
628             return result;
629         }
630 
remove()631         public void remove() {
632             if (lastRet < 0)
633                 throw new IllegalStateException();
634             if (delete(lastRet)) { // if left-shifted, undo increment in next()
635                 cursor = (cursor - 1) & (elements.length - 1);
636                 fence = tail;
637             }
638             lastRet = -1;
639         }
640 
641         @Override
forEachRemaining(Consumer<? super E> action)642         public void forEachRemaining(Consumer<? super E> action) {
643             Objects.requireNonNull(action);
644             Object[] a = elements;
645             int m = a.length - 1, f = fence, i = cursor;
646             cursor = f;
647             while (i != f) {
648                 @SuppressWarnings("unchecked") E e = (E)a[i];
649                 i = (i + 1) & m;
650                 // Android-note: This uses a different heuristic for detecting
651                 // concurrent modification exceptions than next(). As such, this is a less
652                 // precise test.
653                 if (e == null)
654                     throw new ConcurrentModificationException();
655                 action.accept(e);
656             }
657         }
658     }
659 
660     /**
661      * This class is nearly a mirror-image of DeqIterator, using tail
662      * instead of head for initial cursor, and head instead of tail
663      * for fence.
664      */
665     private class DescendingIterator implements Iterator<E> {
666         private int cursor = tail;
667         private int fence = head;
668         private int lastRet = -1;
669 
hasNext()670         public boolean hasNext() {
671             return cursor != fence;
672         }
673 
next()674         public E next() {
675             if (cursor == fence)
676                 throw new NoSuchElementException();
677             cursor = (cursor - 1) & (elements.length - 1);
678             @SuppressWarnings("unchecked")
679             E result = (E) elements[cursor];
680             if (head != fence || result == null)
681                 throw new ConcurrentModificationException();
682             lastRet = cursor;
683             return result;
684         }
685 
remove()686         public void remove() {
687             if (lastRet < 0)
688                 throw new IllegalStateException();
689             if (!delete(lastRet)) {
690                 cursor = (cursor + 1) & (elements.length - 1);
691                 fence = head;
692             }
693             lastRet = -1;
694         }
695     }
696 
697     /**
698      * Returns {@code true} if this deque contains the specified element.
699      * More formally, returns {@code true} if and only if this deque contains
700      * at least one element {@code e} such that {@code o.equals(e)}.
701      *
702      * @param o object to be checked for containment in this deque
703      * @return {@code true} if this deque contains the specified element
704      */
contains(Object o)705     public boolean contains(Object o) {
706         if (o != null) {
707             int mask = elements.length - 1;
708             int i = head;
709             for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
710                 if (o.equals(x))
711                     return true;
712             }
713         }
714         return false;
715     }
716 
717     /**
718      * Removes a single instance of the specified element from this deque.
719      * If the deque does not contain the element, it is unchanged.
720      * More formally, removes the first element {@code e} such that
721      * {@code o.equals(e)} (if such an element exists).
722      * Returns {@code true} if this deque contained the specified element
723      * (or equivalently, if this deque changed as a result of the call).
724      *
725      * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
726      *
727      * @param o element to be removed from this deque, if present
728      * @return {@code true} if this deque contained the specified element
729      */
remove(Object o)730     public boolean remove(Object o) {
731         return removeFirstOccurrence(o);
732     }
733 
734     /**
735      * Removes all of the elements from this deque.
736      * The deque will be empty after this call returns.
737      */
clear()738     public void clear() {
739         int h = head;
740         int t = tail;
741         if (h != t) { // clear all cells
742             head = tail = 0;
743             int i = h;
744             int mask = elements.length - 1;
745             do {
746                 elements[i] = null;
747                 i = (i + 1) & mask;
748             } while (i != t);
749         }
750     }
751 
752     /**
753      * Returns an array containing all of the elements in this deque
754      * in proper sequence (from first to last element).
755      *
756      * <p>The returned array will be "safe" in that no references to it are
757      * maintained by this deque.  (In other words, this method must allocate
758      * a new array).  The caller is thus free to modify the returned array.
759      *
760      * <p>This method acts as bridge between array-based and collection-based
761      * APIs.
762      *
763      * @return an array containing all of the elements in this deque
764      */
toArray()765     public Object[] toArray() {
766         final int head = this.head;
767         final int tail = this.tail;
768         boolean wrap = (tail < head);
769         int end = wrap ? tail + elements.length : tail;
770         Object[] a = Arrays.copyOfRange(elements, head, end);
771         if (wrap)
772             System.arraycopy(elements, 0, a, elements.length - head, tail);
773         return a;
774     }
775 
776     /**
777      * Returns an array containing all of the elements in this deque in
778      * proper sequence (from first to last element); the runtime type of the
779      * returned array is that of the specified array.  If the deque fits in
780      * the specified array, it is returned therein.  Otherwise, a new array
781      * is allocated with the runtime type of the specified array and the
782      * size of this deque.
783      *
784      * <p>If this deque fits in the specified array with room to spare
785      * (i.e., the array has more elements than this deque), the element in
786      * the array immediately following the end of the deque is set to
787      * {@code null}.
788      *
789      * <p>Like the {@link #toArray()} method, this method acts as bridge between
790      * array-based and collection-based APIs.  Further, this method allows
791      * precise control over the runtime type of the output array, and may,
792      * under certain circumstances, be used to save allocation costs.
793      *
794      * <p>Suppose {@code x} is a deque known to contain only strings.
795      * The following code can be used to dump the deque into a newly
796      * allocated array of {@code String}:
797      *
798      * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
799      *
800      * Note that {@code toArray(new Object[0])} is identical in function to
801      * {@code toArray()}.
802      *
803      * @param a the array into which the elements of the deque are to
804      *          be stored, if it is big enough; otherwise, a new array of the
805      *          same runtime type is allocated for this purpose
806      * @return an array containing all of the elements in this deque
807      * @throws ArrayStoreException if the runtime type of the specified array
808      *         is not a supertype of the runtime type of every element in
809      *         this deque
810      * @throws NullPointerException if the specified array is null
811      */
812     @SuppressWarnings("unchecked")
toArray(T[] a)813     public <T> T[] toArray(T[] a) {
814         final int head = this.head;
815         final int tail = this.tail;
816         boolean wrap = (tail < head);
817         int size = (tail - head) + (wrap ? elements.length : 0);
818         int firstLeg = size - (wrap ? tail : 0);
819         int len = a.length;
820         if (size > len) {
821             a = (T[]) Arrays.copyOfRange(elements, head, head + size,
822                                          a.getClass());
823         } else {
824             System.arraycopy(elements, head, a, 0, firstLeg);
825             if (size < len)
826                 a[size] = null;
827         }
828         if (wrap)
829             System.arraycopy(elements, 0, a, firstLeg, tail);
830         return a;
831     }
832 
833     // *** Object methods ***
834 
835     /**
836      * Returns a copy of this deque.
837      *
838      * @return a copy of this deque
839      */
clone()840     public ArrayDeque<E> clone() {
841         try {
842             @SuppressWarnings("unchecked")
843             ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
844             result.elements = Arrays.copyOf(elements, elements.length);
845             return result;
846         } catch (CloneNotSupportedException e) {
847             throw new AssertionError();
848         }
849     }
850 
851     private static final long serialVersionUID = 2340985798034038923L;
852 
853     /**
854      * Saves this deque to a stream (that is, serializes it).
855      *
856      * @param s the stream
857      * @throws java.io.IOException if an I/O error occurs
858      * @serialData The current size ({@code int}) of the deque,
859      * followed by all of its elements (each an object reference) in
860      * first-to-last order.
861      */
writeObject(java.io.ObjectOutputStream s)862     private void writeObject(java.io.ObjectOutputStream s)
863             throws java.io.IOException {
864         s.defaultWriteObject();
865 
866         // Write out size
867         s.writeInt(size());
868 
869         // Write out elements in order.
870         int mask = elements.length - 1;
871         for (int i = head; i != tail; i = (i + 1) & mask)
872             s.writeObject(elements[i]);
873     }
874 
875     /**
876      * Reconstitutes this deque from a stream (that is, deserializes it).
877      * @param s the stream
878      * @throws ClassNotFoundException if the class of a serialized object
879      *         could not be found
880      * @throws java.io.IOException if an I/O error occurs
881      */
readObject(java.io.ObjectInputStream s)882     private void readObject(java.io.ObjectInputStream s)
883             throws java.io.IOException, ClassNotFoundException {
884         s.defaultReadObject();
885 
886         // Read in size and allocate array
887         int size = s.readInt();
888         allocateElements(size);
889         head = 0;
890         tail = size;
891 
892         // Read in all elements in the proper order.
893         for (int i = 0; i < size; i++)
894             elements[i] = s.readObject();
895     }
896 
897     /**
898      * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
899      * and <em>fail-fast</em> {@link Spliterator} over the elements in this
900      * deque.
901      *
902      * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
903      * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
904      * {@link Spliterator#NONNULL}.  Overriding implementations should document
905      * the reporting of additional characteristic values.
906      *
907      * @return a {@code Spliterator} over the elements in this deque
908      * @since 1.8
909      */
spliterator()910     public Spliterator<E> spliterator() {
911         return new DeqSpliterator<>(this, -1, -1);
912     }
913 
914     static final class DeqSpliterator<E> implements Spliterator<E> {
915         private final ArrayDeque<E> deq;
916         private int fence;  // -1 until first use
917         private int index;  // current index, modified on traverse/split
918 
919         /** Creates new spliterator covering the given array and range. */
DeqSpliterator(ArrayDeque<E> deq, int origin, int fence)920         DeqSpliterator(ArrayDeque<E> deq, int origin, int fence) {
921             this.deq = deq;
922             this.index = origin;
923             this.fence = fence;
924         }
925 
getFence()926         private int getFence() { // force initialization
927             int t;
928             if ((t = fence) < 0) {
929                 t = fence = deq.tail;
930                 index = deq.head;
931             }
932             return t;
933         }
934 
trySplit()935         public DeqSpliterator<E> trySplit() {
936             int t = getFence(), h = index, n = deq.elements.length;
937             if (h != t && ((h + 1) & (n - 1)) != t) {
938                 if (h > t)
939                     t += n;
940                 int m = ((h + t) >>> 1) & (n - 1);
941                 return new DeqSpliterator<E>(deq, h, index = m);
942             }
943             return null;
944         }
945 
forEachRemaining(Consumer<? super E> consumer)946         public void forEachRemaining(Consumer<? super E> consumer) {
947             if (consumer == null)
948                 throw new NullPointerException();
949             Object[] a = deq.elements;
950             int m = a.length - 1, f = getFence(), i = index;
951             index = f;
952             while (i != f) {
953                 @SuppressWarnings("unchecked") E e = (E)a[i];
954                 i = (i + 1) & m;
955                 if (e == null)
956                     throw new ConcurrentModificationException();
957                 consumer.accept(e);
958             }
959         }
960 
tryAdvance(Consumer<? super E> consumer)961         public boolean tryAdvance(Consumer<? super E> consumer) {
962             if (consumer == null)
963                 throw new NullPointerException();
964             Object[] a = deq.elements;
965             int m = a.length - 1, f = getFence(), i = index;
966             if (i != f) {
967                 @SuppressWarnings("unchecked") E e = (E)a[i];
968                 index = (i + 1) & m;
969                 if (e == null)
970                     throw new ConcurrentModificationException();
971                 consumer.accept(e);
972                 return true;
973             }
974             return false;
975         }
976 
estimateSize()977         public long estimateSize() {
978             int n = getFence() - index;
979             if (n < 0)
980                 n += deq.elements.length;
981             return (long) n;
982         }
983 
984         @Override
characteristics()985         public int characteristics() {
986             return Spliterator.ORDERED | Spliterator.SIZED |
987                 Spliterator.NONNULL | Spliterator.SUBSIZED;
988         }
989     }
990 
991 }
992