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 import java.util.function.Predicate;
40 import jdk.internal.access.SharedSecrets;
41 
42 /**
43  * Resizable-array implementation of the {@link Deque} interface.  Array
44  * deques have no capacity restrictions; they grow as necessary to support
45  * usage.  They are not thread-safe; in the absence of external
46  * synchronization, they do not support concurrent access by multiple threads.
47  * Null elements are prohibited.  This class is likely to be faster than
48  * {@link Stack} when used as a stack, and faster than {@link LinkedList}
49  * when used as a queue.
50  *
51  * <p>Most {@code ArrayDeque} operations run in amortized constant time.
52  * Exceptions include
53  * {@link #remove(Object) remove},
54  * {@link #removeFirstOccurrence removeFirstOccurrence},
55  * {@link #removeLastOccurrence removeLastOccurrence},
56  * {@link #contains contains},
57  * {@link #iterator iterator.remove()},
58  * and the bulk operations, all of which run in linear time.
59  *
60  * <p>The iterators returned by this class's {@link #iterator() iterator}
61  * method are <em>fail-fast</em>: If the deque is modified at any time after
62  * the iterator is created, in any way except through the iterator's own
63  * {@code remove} method, the iterator will generally throw a {@link
64  * ConcurrentModificationException}.  Thus, in the face of concurrent
65  * modification, the iterator fails quickly and cleanly, rather than risking
66  * arbitrary, non-deterministic behavior at an undetermined time in the
67  * future.
68  *
69  * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
70  * as it is, generally speaking, impossible to make any hard guarantees in the
71  * presence of unsynchronized concurrent modification.  Fail-fast iterators
72  * throw {@code ConcurrentModificationException} on a best-effort basis.
73  * Therefore, it would be wrong to write a program that depended on this
74  * exception for its correctness: <i>the fail-fast behavior of iterators
75  * should be used only to detect bugs.</i>
76  *
77  * <p>This class and its iterator implement all of the <em>optional</em> methods of the
78  * {@link Collection}, {@link SequencedCollection}, and {@link Iterator} interfaces.
79  *
80  * <p>This class is a member of the
81  * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
82  * Java Collections Framework</a>.
83  *
84  * @author  Josh Bloch and Doug Lea
85  * @param <E> the type of elements held in this deque
86  * @since   1.6
87  */
88 public class ArrayDeque<E> extends AbstractCollection<E>
89                            implements Deque<E>, Cloneable, Serializable
90 {
91     /*
92      * VMs excel at optimizing simple array loops where indices are
93      * incrementing or decrementing over a valid slice, e.g.
94      *
95      * for (int i = start; i < end; i++) ... elements[i]
96      *
97      * Because in a circular array, elements are in general stored in
98      * two disjoint such slices, we help the VM by writing unusual
99      * nested loops for all traversals over the elements.  Having only
100      * one hot inner loop body instead of two or three eases human
101      * maintenance and encourages VM loop inlining into the caller.
102      */
103 
104     /**
105      * The array in which the elements of the deque are stored.
106      * All array cells not holding deque elements are always null.
107      * The array always has at least one null slot (at tail).
108      */
109     transient Object[] elements;
110 
111     /**
112      * The index of the element at the head of the deque (which is the
113      * element that would be removed by remove() or pop()); or an
114      * arbitrary number 0 <= head < elements.length equal to tail if
115      * the deque is empty.
116      */
117     transient int head;
118 
119     /**
120      * The index at which the next element would be added to the tail
121      * of the deque (via addLast(E), add(E), or push(E));
122      * elements[tail] is always null.
123      */
124     transient int tail;
125 
126     /**
127      * The maximum size of array to allocate.
128      * Some VMs reserve some header words in an array.
129      * Attempts to allocate larger arrays may result in
130      * OutOfMemoryError: Requested array size exceeds VM limit
131      */
132     private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
133 
134     /**
135      * Increases the capacity of this deque by at least the given amount.
136      *
137      * @param needed the required minimum extra capacity; must be positive
138      */
grow(int needed)139     private void grow(int needed) {
140         // overflow-conscious code
141         final int oldCapacity = elements.length;
142         int newCapacity;
143         // Double capacity if small; else grow by 50%
144         int jump = (oldCapacity < 64) ? (oldCapacity + 2) : (oldCapacity >> 1);
145         if (jump < needed
146             || (newCapacity = (oldCapacity + jump)) - MAX_ARRAY_SIZE > 0)
147             newCapacity = newCapacity(needed, jump);
148         // Android-added: preserve reference to the old storage to nullify it later.
149         final Object[] oldElements = elements;
150         final Object[] es = elements = Arrays.copyOf(elements, newCapacity);
151         // Exceptionally, here tail == head needs to be disambiguated
152         if (tail < head || (tail == head && es[head] != null)) {
153             // wrap around; slide first leg forward to end of array
154             int newSpace = newCapacity - oldCapacity;
155             System.arraycopy(es, head,
156                              es, head + newSpace,
157                              oldCapacity - head);
158             for (int i = head, to = (head += newSpace); i < to; i++)
159                 es[i] = null;
160         }
161         // Android-added: Clear old array instance that's about to become eligible for GC.
162         // This ensures that array elements can be eligible for garbage collection even
163         // before the array itself is recognized as being eligible; the latter might
164         // take a while in some GC implementations, if the array instance is longer lived
165         // (its liveness rarely checked) than some of its contents.
166         Arrays.fill(oldElements, null);
167     }
168 
169     /** Capacity calculation for edge conditions, especially overflow. */
newCapacity(int needed, int jump)170     private int newCapacity(int needed, int jump) {
171         final int oldCapacity = elements.length, minCapacity;
172         if ((minCapacity = oldCapacity + needed) - MAX_ARRAY_SIZE > 0) {
173             if (minCapacity < 0)
174                 throw new IllegalStateException("Sorry, deque too big");
175             return Integer.MAX_VALUE;
176         }
177         if (needed > jump)
178             return minCapacity;
179         return (oldCapacity + jump - MAX_ARRAY_SIZE < 0)
180             ? oldCapacity + jump
181             : MAX_ARRAY_SIZE;
182     }
183 
184     /**
185      * Constructs an empty array deque with an initial capacity
186      * sufficient to hold 16 elements.
187      */
ArrayDeque()188     public ArrayDeque() {
189         elements = new Object[16 + 1];
190     }
191 
192     /**
193      * Constructs an empty array deque with an initial capacity
194      * sufficient to hold the specified number of elements.
195      *
196      * @param numElements lower bound on initial capacity of the deque
197      */
ArrayDeque(int numElements)198     public ArrayDeque(int numElements) {
199         elements =
200             new Object[(numElements < 1) ? 1 :
201                        (numElements == Integer.MAX_VALUE) ? Integer.MAX_VALUE :
202                        numElements + 1];
203     }
204 
205     /**
206      * Constructs a deque containing the elements of the specified
207      * collection, in the order they are returned by the collection's
208      * iterator.  (The first element returned by the collection's
209      * iterator becomes the first element, or <i>front</i> of the
210      * deque.)
211      *
212      * @param c the collection whose elements are to be placed into the deque
213      * @throws NullPointerException if the specified collection is null
214      */
ArrayDeque(Collection<? extends E> c)215     public ArrayDeque(Collection<? extends E> c) {
216         this(c.size());
217         copyElements(c);
218     }
219 
220     /**
221      * Circularly increments i, mod modulus.
222      * Precondition and postcondition: 0 <= i < modulus.
223      */
inc(int i, int modulus)224     static final int inc(int i, int modulus) {
225         if (++i >= modulus) i = 0;
226         return i;
227     }
228 
229     /**
230      * Circularly decrements i, mod modulus.
231      * Precondition and postcondition: 0 <= i < modulus.
232      */
dec(int i, int modulus)233     static final int dec(int i, int modulus) {
234         if (--i < 0) i = modulus - 1;
235         return i;
236     }
237 
238     /**
239      * Circularly adds the given distance to index i, mod modulus.
240      * Precondition: 0 <= i < modulus, 0 <= distance <= modulus.
241      * @return index 0 <= i < modulus
242      */
inc(int i, int distance, int modulus)243     static final int inc(int i, int distance, int modulus) {
244         if ((i += distance) - modulus >= 0) i -= modulus;
245         return i;
246     }
247 
248     /**
249      * Subtracts j from i, mod modulus.
250      * Index i must be logically ahead of index j.
251      * Precondition: 0 <= i < modulus, 0 <= j < modulus.
252      * @return the "circular distance" from j to i; corner case i == j
253      * is disambiguated to "empty", returning 0.
254      */
sub(int i, int j, int modulus)255     static final int sub(int i, int j, int modulus) {
256         if ((i -= j) < 0) i += modulus;
257         return i;
258     }
259 
260     /**
261      * Returns element at array index i.
262      * This is a slight abuse of generics, accepted by javac.
263      */
264     @SuppressWarnings("unchecked")
elementAt(Object[] es, int i)265     static final <E> E elementAt(Object[] es, int i) {
266         return (E) es[i];
267     }
268 
269     /**
270      * A version of elementAt that checks for null elements.
271      * This check doesn't catch all possible comodifications,
272      * but does catch ones that corrupt traversal.
273      */
nonNullElementAt(Object[] es, int i)274     static final <E> E nonNullElementAt(Object[] es, int i) {
275         @SuppressWarnings("unchecked") E e = (E) es[i];
276         if (e == null)
277             throw new ConcurrentModificationException();
278         return e;
279     }
280 
281     // The main insertion and extraction methods are addFirst,
282     // addLast, pollFirst, pollLast. The other methods are defined in
283     // terms of these.
284 
285     /**
286      * Inserts the specified element at the front of this deque.
287      *
288      * @param e the element to add
289      * @throws NullPointerException if the specified element is null
290      */
addFirst(E e)291     public void addFirst(E e) {
292         if (e == null)
293             throw new NullPointerException();
294         final Object[] es = elements;
295         es[head = dec(head, es.length)] = e;
296         if (head == tail)
297             grow(1);
298     }
299 
300     /**
301      * Inserts the specified element at the end of this deque.
302      *
303      * <p>This method is equivalent to {@link #add}.
304      *
305      * @param e the element to add
306      * @throws NullPointerException if the specified element is null
307      */
addLast(E e)308     public void addLast(E e) {
309         if (e == null)
310             throw new NullPointerException();
311         final Object[] es = elements;
312         es[tail] = e;
313         if (head == (tail = inc(tail, es.length)))
314             grow(1);
315     }
316 
317     /**
318      * Adds all of the elements in the specified collection at the end
319      * of this deque, as if by calling {@link #addLast} on each one,
320      * in the order that they are returned by the collection's iterator.
321      *
322      * @param c the elements to be inserted into this deque
323      * @return {@code true} if this deque changed as a result of the call
324      * @throws NullPointerException if the specified collection or any
325      *         of its elements are null
326      */
addAll(Collection<? extends E> c)327     public boolean addAll(Collection<? extends E> c) {
328         final int s, needed;
329         if ((needed = (s = size()) + c.size() + 1 - elements.length) > 0)
330             grow(needed);
331         copyElements(c);
332         return size() > s;
333     }
334 
copyElements(Collection<? extends E> c)335     private void copyElements(Collection<? extends E> c) {
336         c.forEach(this::addLast);
337     }
338 
339     /**
340      * Inserts the specified element at the front of this deque.
341      *
342      * @param e the element to add
343      * @return {@code true} (as specified by {@link Deque#offerFirst})
344      * @throws NullPointerException if the specified element is null
345      */
offerFirst(E e)346     public boolean offerFirst(E e) {
347         addFirst(e);
348         return true;
349     }
350 
351     /**
352      * Inserts the specified element at the end of this deque.
353      *
354      * @param e the element to add
355      * @return {@code true} (as specified by {@link Deque#offerLast})
356      * @throws NullPointerException if the specified element is null
357      */
offerLast(E e)358     public boolean offerLast(E e) {
359         addLast(e);
360         return true;
361     }
362 
363     /**
364      * @throws NoSuchElementException {@inheritDoc}
365      */
removeFirst()366     public E removeFirst() {
367         E e = pollFirst();
368         if (e == null)
369             throw new NoSuchElementException();
370         return e;
371     }
372 
373     /**
374      * @throws NoSuchElementException {@inheritDoc}
375      */
removeLast()376     public E removeLast() {
377         E e = pollLast();
378         if (e == null)
379             throw new NoSuchElementException();
380         return e;
381     }
382 
pollFirst()383     public E pollFirst() {
384         final Object[] es;
385         final int h;
386         E e = elementAt(es = elements, h = head);
387         if (e != null) {
388             es[h] = null;
389             head = inc(h, es.length);
390         }
391         return e;
392     }
393 
pollLast()394     public E pollLast() {
395         final Object[] es;
396         final int t;
397         E e = elementAt(es = elements, t = dec(tail, es.length));
398         if (e != null)
399             es[tail = t] = null;
400         return e;
401     }
402 
403     /**
404      * @throws NoSuchElementException {@inheritDoc}
405      */
getFirst()406     public E getFirst() {
407         E e = elementAt(elements, head);
408         if (e == null)
409             throw new NoSuchElementException();
410         return e;
411     }
412 
413     /**
414      * @throws NoSuchElementException {@inheritDoc}
415      */
getLast()416     public E getLast() {
417         final Object[] es = elements;
418         E e = elementAt(es, dec(tail, es.length));
419         if (e == null)
420             throw new NoSuchElementException();
421         return e;
422     }
423 
peekFirst()424     public E peekFirst() {
425         return elementAt(elements, head);
426     }
427 
peekLast()428     public E peekLast() {
429         final Object[] es;
430         return elementAt(es = elements, dec(tail, es.length));
431     }
432 
433     /**
434      * Removes the first occurrence of the specified element in this
435      * deque (when traversing the deque from head to tail).
436      * If the deque does not contain the element, it is unchanged.
437      * More formally, removes the first element {@code e} such that
438      * {@code o.equals(e)} (if such an element exists).
439      * Returns {@code true} if this deque contained the specified element
440      * (or equivalently, if this deque changed as a result of the call).
441      *
442      * @param o element to be removed from this deque, if present
443      * @return {@code true} if the deque contained the specified element
444      */
removeFirstOccurrence(Object o)445     public boolean removeFirstOccurrence(Object o) {
446         if (o != null) {
447             final Object[] es = elements;
448             for (int i = head, end = tail, to = (i <= end) ? end : es.length;
449                  ; i = 0, to = end) {
450                 for (; i < to; i++)
451                     if (o.equals(es[i])) {
452                         delete(i);
453                         return true;
454                     }
455                 if (to == end) break;
456             }
457         }
458         return false;
459     }
460 
461     /**
462      * Removes the last occurrence of the specified element in this
463      * deque (when traversing the deque from head to tail).
464      * If the deque does not contain the element, it is unchanged.
465      * More formally, removes the last element {@code e} such that
466      * {@code o.equals(e)} (if such an element exists).
467      * Returns {@code true} if this deque contained the specified element
468      * (or equivalently, if this deque changed as a result of the call).
469      *
470      * @param o element to be removed from this deque, if present
471      * @return {@code true} if the deque contained the specified element
472      */
removeLastOccurrence(Object o)473     public boolean removeLastOccurrence(Object o) {
474         if (o != null) {
475             final Object[] es = elements;
476             for (int i = tail, end = head, to = (i >= end) ? end : 0;
477                  ; i = es.length, to = end) {
478                 for (i--; i > to - 1; i--)
479                     if (o.equals(es[i])) {
480                         delete(i);
481                         return true;
482                     }
483                 if (to == end) break;
484             }
485         }
486         return false;
487     }
488 
489     // *** Queue methods ***
490 
491     /**
492      * Inserts the specified element at the end of this deque.
493      *
494      * <p>This method is equivalent to {@link #addLast}.
495      *
496      * @param e the element to add
497      * @return {@code true} (as specified by {@link Collection#add})
498      * @throws NullPointerException if the specified element is null
499      */
add(E e)500     public boolean add(E e) {
501         addLast(e);
502         return true;
503     }
504 
505     /**
506      * Inserts the specified element at the end of this deque.
507      *
508      * <p>This method is equivalent to {@link #offerLast}.
509      *
510      * @param e the element to add
511      * @return {@code true} (as specified by {@link Queue#offer})
512      * @throws NullPointerException if the specified element is null
513      */
offer(E e)514     public boolean offer(E e) {
515         return offerLast(e);
516     }
517 
518     /**
519      * Retrieves and removes the head of the queue represented by this deque.
520      *
521      * This method differs from {@link #poll() poll()} only in that it
522      * throws an exception if this deque is empty.
523      *
524      * <p>This method is equivalent to {@link #removeFirst}.
525      *
526      * @return the head of the queue represented by this deque
527      * @throws NoSuchElementException {@inheritDoc}
528      */
remove()529     public E remove() {
530         return removeFirst();
531     }
532 
533     /**
534      * Retrieves and removes the head of the queue represented by this deque
535      * (in other words, the first element of this deque), or returns
536      * {@code null} if this deque is empty.
537      *
538      * <p>This method is equivalent to {@link #pollFirst}.
539      *
540      * @return the head of the queue represented by this deque, or
541      *         {@code null} if this deque is empty
542      */
poll()543     public E poll() {
544         return pollFirst();
545     }
546 
547     /**
548      * Retrieves, but does not remove, the head of the queue represented by
549      * this deque.  This method differs from {@link #peek peek} only in
550      * that it throws an exception if this deque is empty.
551      *
552      * <p>This method is equivalent to {@link #getFirst}.
553      *
554      * @return the head of the queue represented by this deque
555      * @throws NoSuchElementException {@inheritDoc}
556      */
element()557     public E element() {
558         return getFirst();
559     }
560 
561     /**
562      * Retrieves, but does not remove, the head of the queue represented by
563      * this deque, or returns {@code null} if this deque is empty.
564      *
565      * <p>This method is equivalent to {@link #peekFirst}.
566      *
567      * @return the head of the queue represented by this deque, or
568      *         {@code null} if this deque is empty
569      */
peek()570     public E peek() {
571         return peekFirst();
572     }
573 
574     // *** Stack methods ***
575 
576     /**
577      * Pushes an element onto the stack represented by this deque.  In other
578      * words, inserts the element at the front of this deque.
579      *
580      * <p>This method is equivalent to {@link #addFirst}.
581      *
582      * @param e the element to push
583      * @throws NullPointerException if the specified element is null
584      */
push(E e)585     public void push(E e) {
586         addFirst(e);
587     }
588 
589     /**
590      * Pops an element from the stack represented by this deque.  In other
591      * words, removes and returns the first element of this deque.
592      *
593      * <p>This method is equivalent to {@link #removeFirst()}.
594      *
595      * @return the element at the front of this deque (which is the top
596      *         of the stack represented by this deque)
597      * @throws NoSuchElementException {@inheritDoc}
598      */
pop()599     public E pop() {
600         return removeFirst();
601     }
602 
603     /**
604      * Removes the element at the specified position in the elements array.
605      * This can result in forward or backwards motion of array elements.
606      * We optimize for least element motion.
607      *
608      * <p>This method is called delete rather than remove to emphasize
609      * that its semantics differ from those of {@link List#remove(int)}.
610      *
611      * @return true if elements near tail moved backwards
612      */
delete(int i)613     boolean delete(int i) {
614         final Object[] es = elements;
615         final int capacity = es.length;
616         final int h, t;
617         // number of elements before to-be-deleted elt
618         final int front = sub(i, h = head, capacity);
619         // number of elements after to-be-deleted elt
620         final int back = sub(t = tail, i, capacity) - 1;
621         if (front < back) {
622             // move front elements forwards
623             if (h <= i) {
624                 System.arraycopy(es, h, es, h + 1, front);
625             } else { // Wrap around
626                 System.arraycopy(es, 0, es, 1, i);
627                 es[0] = es[capacity - 1];
628                 System.arraycopy(es, h, es, h + 1, front - (i + 1));
629             }
630             es[h] = null;
631             head = inc(h, capacity);
632             return false;
633         } else {
634             // move back elements backwards
635             tail = dec(t, capacity);
636             if (i <= tail) {
637                 System.arraycopy(es, i + 1, es, i, back);
638             } else { // Wrap around
639                 System.arraycopy(es, i + 1, es, i, capacity - (i + 1));
640                 es[capacity - 1] = es[0];
641                 System.arraycopy(es, 1, es, 0, t - 1);
642             }
643             es[tail] = null;
644             return true;
645         }
646     }
647 
648     // *** Collection Methods ***
649 
650     /**
651      * Returns the number of elements in this deque.
652      *
653      * @return the number of elements in this deque
654      */
size()655     public int size() {
656         return sub(tail, head, elements.length);
657     }
658 
659     /**
660      * Returns {@code true} if this deque contains no elements.
661      *
662      * @return {@code true} if this deque contains no elements
663      */
isEmpty()664     public boolean isEmpty() {
665         return head == tail;
666     }
667 
668     /**
669      * Returns an iterator over the elements in this deque.  The elements
670      * will be ordered from first (head) to last (tail).  This is the same
671      * order that elements would be dequeued (via successive calls to
672      * {@link #remove} or popped (via successive calls to {@link #pop}).
673      *
674      * @return an iterator over the elements in this deque
675      */
iterator()676     public Iterator<E> iterator() {
677         return new DeqIterator();
678     }
679 
descendingIterator()680     public Iterator<E> descendingIterator() {
681         return new DescendingIterator();
682     }
683 
684     private class DeqIterator implements Iterator<E> {
685         /** Index of element to be returned by subsequent call to next. */
686         int cursor;
687 
688         /** Number of elements yet to be returned. */
689         int remaining = size();
690 
691         /**
692          * Index of element returned by most recent call to next.
693          * Reset to -1 if element is deleted by a call to remove.
694          */
695         int lastRet = -1;
696 
DeqIterator()697         DeqIterator() { cursor = head; }
698 
hasNext()699         public final boolean hasNext() {
700             return remaining > 0;
701         }
702 
next()703         public E next() {
704             if (remaining <= 0)
705                 throw new NoSuchElementException();
706             final Object[] es = elements;
707             E e = nonNullElementAt(es, cursor);
708             cursor = inc(lastRet = cursor, es.length);
709             remaining--;
710             return e;
711         }
712 
postDelete(boolean leftShifted)713         void postDelete(boolean leftShifted) {
714             if (leftShifted)
715                 cursor = dec(cursor, elements.length);
716         }
717 
remove()718         public final void remove() {
719             if (lastRet < 0)
720                 throw new IllegalStateException();
721             postDelete(delete(lastRet));
722             lastRet = -1;
723         }
724 
725         @Override
forEachRemaining(Consumer<? super E> action)726         public void forEachRemaining(Consumer<? super E> action) {
727             Objects.requireNonNull(action);
728             int r;
729             if ((r = remaining) <= 0)
730                 return;
731             remaining = 0;
732             final Object[] es = elements;
733             if (es[cursor] == null || sub(tail, cursor, es.length) != r)
734                 throw new ConcurrentModificationException();
735             for (int i = cursor, end = tail, to = (i <= end) ? end : es.length;
736                  ; i = 0, to = end) {
737                 for (; i < to; i++)
738                     action.accept(elementAt(es, i));
739                 if (to == end) {
740                     if (end != tail)
741                         throw new ConcurrentModificationException();
742                     lastRet = dec(end, es.length);
743                     break;
744                 }
745             }
746         }
747     }
748 
749     private class DescendingIterator extends DeqIterator {
DescendingIterator()750         DescendingIterator() { cursor = dec(tail, elements.length); }
751 
next()752         public final E next() {
753             if (remaining <= 0)
754                 throw new NoSuchElementException();
755             final Object[] es = elements;
756             E e = nonNullElementAt(es, cursor);
757             cursor = dec(lastRet = cursor, es.length);
758             remaining--;
759             return e;
760         }
761 
postDelete(boolean leftShifted)762         void postDelete(boolean leftShifted) {
763             if (!leftShifted)
764                 cursor = inc(cursor, elements.length);
765         }
766 
forEachRemaining(Consumer<? super E> action)767         public final void forEachRemaining(Consumer<? super E> action) {
768             Objects.requireNonNull(action);
769             int r;
770             if ((r = remaining) <= 0)
771                 return;
772             remaining = 0;
773             final Object[] es = elements;
774             if (es[cursor] == null || sub(cursor, head, es.length) + 1 != r)
775                 throw new ConcurrentModificationException();
776             for (int i = cursor, end = head, to = (i >= end) ? end : 0;
777                  ; i = es.length - 1, to = end) {
778                 // hotspot generates faster code than for: i >= to !
779                 for (; i > to - 1; i--)
780                     action.accept(elementAt(es, i));
781                 if (to == end) {
782                     if (end != head)
783                         throw new ConcurrentModificationException();
784                     lastRet = end;
785                     break;
786                 }
787             }
788         }
789     }
790 
791     /**
792      * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
793      * and <em>fail-fast</em> {@link Spliterator} over the elements in this
794      * deque.
795      *
796      * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
797      * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
798      * {@link Spliterator#NONNULL}.  Overriding implementations should document
799      * the reporting of additional characteristic values.
800      *
801      * @return a {@code Spliterator} over the elements in this deque
802      * @since 1.8
803      */
spliterator()804     public Spliterator<E> spliterator() {
805         return new DeqSpliterator();
806     }
807 
808     final class DeqSpliterator implements Spliterator<E> {
809         private int fence;      // -1 until first use
810         private int cursor;     // current index, modified on traverse/split
811 
812         /** Constructs late-binding spliterator over all elements. */
DeqSpliterator()813         DeqSpliterator() {
814             this.fence = -1;
815         }
816 
817         /** Constructs spliterator over the given range. */
DeqSpliterator(int origin, int fence)818         DeqSpliterator(int origin, int fence) {
819             // assert 0 <= origin && origin < elements.length;
820             // assert 0 <= fence && fence < elements.length;
821             this.cursor = origin;
822             this.fence = fence;
823         }
824 
825         /** Ensures late-binding initialization; then returns fence. */
getFence()826         private int getFence() { // force initialization
827             int t;
828             if ((t = fence) < 0) {
829                 t = fence = tail;
830                 cursor = head;
831             }
832             return t;
833         }
834 
trySplit()835         public DeqSpliterator trySplit() {
836             final Object[] es = elements;
837             final int i, n;
838             return ((n = sub(getFence(), i = cursor, es.length) >> 1) <= 0)
839                 ? null
840                 : new DeqSpliterator(i, cursor = inc(i, n, es.length));
841         }
842 
forEachRemaining(Consumer<? super E> action)843         public void forEachRemaining(Consumer<? super E> action) {
844             if (action == null)
845                 throw new NullPointerException();
846             final int end = getFence(), cursor = this.cursor;
847             final Object[] es = elements;
848             if (cursor != end) {
849                 this.cursor = end;
850                 // null check at both ends of range is sufficient
851                 if (es[cursor] == null || es[dec(end, es.length)] == null)
852                     throw new ConcurrentModificationException();
853                 for (int i = cursor, to = (i <= end) ? end : es.length;
854                      ; i = 0, to = end) {
855                     for (; i < to; i++)
856                         action.accept(elementAt(es, i));
857                     if (to == end) break;
858                 }
859             }
860         }
861 
tryAdvance(Consumer<? super E> action)862         public boolean tryAdvance(Consumer<? super E> action) {
863             Objects.requireNonNull(action);
864             final Object[] es = elements;
865             if (fence < 0) { fence = tail; cursor = head; } // late-binding
866             final int i;
867             if ((i = cursor) == fence)
868                 return false;
869             E e = nonNullElementAt(es, i);
870             cursor = inc(i, es.length);
871             action.accept(e);
872             return true;
873         }
874 
estimateSize()875         public long estimateSize() {
876             return sub(getFence(), cursor, elements.length);
877         }
878 
characteristics()879         public int characteristics() {
880             return Spliterator.NONNULL
881                 | Spliterator.ORDERED
882                 | Spliterator.SIZED
883                 | Spliterator.SUBSIZED;
884         }
885     }
886 
887     /**
888      * @throws NullPointerException {@inheritDoc}
889      */
forEach(Consumer<? super E> action)890     public void forEach(Consumer<? super E> action) {
891         Objects.requireNonNull(action);
892         final Object[] es = elements;
893         for (int i = head, end = tail, to = (i <= end) ? end : es.length;
894              ; i = 0, to = end) {
895             for (; i < to; i++)
896                 action.accept(elementAt(es, i));
897             if (to == end) {
898                 if (end != tail) throw new ConcurrentModificationException();
899                 break;
900             }
901         }
902     }
903 
904     /**
905      * @throws NullPointerException {@inheritDoc}
906      */
removeIf(Predicate<? super E> filter)907     public boolean removeIf(Predicate<? super E> filter) {
908         Objects.requireNonNull(filter);
909         return bulkRemove(filter);
910     }
911 
912     /**
913      * @throws NullPointerException {@inheritDoc}
914      */
removeAll(Collection<?> c)915     public boolean removeAll(Collection<?> c) {
916         Objects.requireNonNull(c);
917         return bulkRemove(e -> c.contains(e));
918     }
919 
920     /**
921      * @throws NullPointerException {@inheritDoc}
922      */
retainAll(Collection<?> c)923     public boolean retainAll(Collection<?> c) {
924         Objects.requireNonNull(c);
925         return bulkRemove(e -> !c.contains(e));
926     }
927 
928     /** Implementation of bulk remove methods. */
bulkRemove(Predicate<? super E> filter)929     private boolean bulkRemove(Predicate<? super E> filter) {
930         final Object[] es = elements;
931         // Optimize for initial run of survivors
932         for (int i = head, end = tail, to = (i <= end) ? end : es.length;
933              ; i = 0, to = end) {
934             for (; i < to; i++)
935                 if (filter.test(elementAt(es, i)))
936                     return bulkRemoveModified(filter, i);
937             if (to == end) {
938                 if (end != tail) throw new ConcurrentModificationException();
939                 break;
940             }
941         }
942         return false;
943     }
944 
945     // A tiny bit set implementation
946 
nBits(int n)947     private static long[] nBits(int n) {
948         return new long[((n - 1) >> 6) + 1];
949     }
setBit(long[] bits, int i)950     private static void setBit(long[] bits, int i) {
951         bits[i >> 6] |= 1L << i;
952     }
isClear(long[] bits, int i)953     private static boolean isClear(long[] bits, int i) {
954         return (bits[i >> 6] & (1L << i)) == 0;
955     }
956 
957     /**
958      * Helper for bulkRemove, in case of at least one deletion.
959      * Tolerate predicates that reentrantly access the collection for
960      * read (but writers still get CME), so traverse once to find
961      * elements to delete, a second pass to physically expunge.
962      *
963      * @param beg valid index of first element to be deleted
964      */
bulkRemoveModified( Predicate<? super E> filter, final int beg)965     private boolean bulkRemoveModified(
966         Predicate<? super E> filter, final int beg) {
967         final Object[] es = elements;
968         final int capacity = es.length;
969         final int end = tail;
970         final long[] deathRow = nBits(sub(end, beg, capacity));
971         deathRow[0] = 1L;   // set bit 0
972         for (int i = beg + 1, to = (i <= end) ? end : es.length, k = beg;
973              ; i = 0, to = end, k -= capacity) {
974             for (; i < to; i++)
975                 if (filter.test(elementAt(es, i)))
976                     setBit(deathRow, i - k);
977             if (to == end) break;
978         }
979         // a two-finger traversal, with hare i reading, tortoise w writing
980         int w = beg;
981         for (int i = beg + 1, to = (i <= end) ? end : es.length, k = beg;
982              ; w = 0) { // w rejoins i on second leg
983             // In this loop, i and w are on the same leg, with i > w
984             for (; i < to; i++)
985                 if (isClear(deathRow, i - k))
986                     es[w++] = es[i];
987             if (to == end) break;
988             // In this loop, w is on the first leg, i on the second
989             for (i = 0, to = end, k -= capacity; i < to && w < capacity; i++)
990                 if (isClear(deathRow, i - k))
991                     es[w++] = es[i];
992             if (i >= to) {
993                 if (w == capacity) w = 0; // "corner" case
994                 break;
995             }
996         }
997         if (end != tail) throw new ConcurrentModificationException();
998         circularClear(es, tail = w, end);
999         return true;
1000     }
1001 
1002     /**
1003      * Returns {@code true} if this deque contains the specified element.
1004      * More formally, returns {@code true} if and only if this deque contains
1005      * at least one element {@code e} such that {@code o.equals(e)}.
1006      *
1007      * @param o object to be checked for containment in this deque
1008      * @return {@code true} if this deque contains the specified element
1009      */
contains(Object o)1010     public boolean contains(Object o) {
1011         if (o != null) {
1012             final Object[] es = elements;
1013             for (int i = head, end = tail, to = (i <= end) ? end : es.length;
1014                  ; i = 0, to = end) {
1015                 for (; i < to; i++)
1016                     if (o.equals(es[i]))
1017                         return true;
1018                 if (to == end) break;
1019             }
1020         }
1021         return false;
1022     }
1023 
1024     /**
1025      * Removes a single instance of the specified element from this deque.
1026      * If the deque does not contain the element, it is unchanged.
1027      * More formally, removes the first element {@code e} such that
1028      * {@code o.equals(e)} (if such an element exists).
1029      * Returns {@code true} if this deque contained the specified element
1030      * (or equivalently, if this deque changed as a result of the call).
1031      *
1032      * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
1033      *
1034      * @param o element to be removed from this deque, if present
1035      * @return {@code true} if this deque contained the specified element
1036      */
remove(Object o)1037     public boolean remove(Object o) {
1038         return removeFirstOccurrence(o);
1039     }
1040 
1041     /**
1042      * Removes all of the elements from this deque.
1043      * The deque will be empty after this call returns.
1044      */
clear()1045     public void clear() {
1046         circularClear(elements, head, tail);
1047         head = tail = 0;
1048     }
1049 
1050     /**
1051      * Nulls out slots starting at array index i, up to index end.
1052      * Condition i == end means "empty" - nothing to do.
1053      */
circularClear(Object[] es, int i, int end)1054     private static void circularClear(Object[] es, int i, int end) {
1055         // assert 0 <= i && i < es.length;
1056         // assert 0 <= end && end < es.length;
1057         for (int to = (i <= end) ? end : es.length;
1058              ; i = 0, to = end) {
1059             for (; i < to; i++) es[i] = null;
1060             if (to == end) break;
1061         }
1062     }
1063 
1064     /**
1065      * Returns an array containing all of the elements in this deque
1066      * in proper sequence (from first to last element).
1067      *
1068      * <p>The returned array will be "safe" in that no references to it are
1069      * maintained by this deque.  (In other words, this method must allocate
1070      * a new array).  The caller is thus free to modify the returned array.
1071      *
1072      * <p>This method acts as bridge between array-based and collection-based
1073      * APIs.
1074      *
1075      * @return an array containing all of the elements in this deque
1076      */
toArray()1077     public Object[] toArray() {
1078         return toArray(Object[].class);
1079     }
1080 
toArray(Class<T[]> klazz)1081     private <T> T[] toArray(Class<T[]> klazz) {
1082         final Object[] es = elements;
1083         final T[] a;
1084         final int head = this.head, tail = this.tail, end;
1085         if ((end = tail + ((head <= tail) ? 0 : es.length)) >= 0) {
1086             // Uses null extension feature of copyOfRange
1087             a = Arrays.copyOfRange(es, head, end, klazz);
1088         } else {
1089             // integer overflow!
1090             a = Arrays.copyOfRange(es, 0, end - head, klazz);
1091             System.arraycopy(es, head, a, 0, es.length - head);
1092         }
1093         if (end != tail)
1094             System.arraycopy(es, 0, a, es.length - head, tail);
1095         return a;
1096     }
1097 
1098     /**
1099      * Returns an array containing all of the elements in this deque in
1100      * proper sequence (from first to last element); the runtime type of the
1101      * returned array is that of the specified array.  If the deque fits in
1102      * the specified array, it is returned therein.  Otherwise, a new array
1103      * is allocated with the runtime type of the specified array and the
1104      * size of this deque.
1105      *
1106      * <p>If this deque fits in the specified array with room to spare
1107      * (i.e., the array has more elements than this deque), the element in
1108      * the array immediately following the end of the deque is set to
1109      * {@code null}.
1110      *
1111      * <p>Like the {@link #toArray()} method, this method acts as bridge between
1112      * array-based and collection-based APIs.  Further, this method allows
1113      * precise control over the runtime type of the output array, and may,
1114      * under certain circumstances, be used to save allocation costs.
1115      *
1116      * <p>Suppose {@code x} is a deque known to contain only strings.
1117      * The following code can be used to dump the deque into a newly
1118      * allocated array of {@code String}:
1119      *
1120      * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
1121      *
1122      * Note that {@code toArray(new Object[0])} is identical in function to
1123      * {@code toArray()}.
1124      *
1125      * @param a the array into which the elements of the deque are to
1126      *          be stored, if it is big enough; otherwise, a new array of the
1127      *          same runtime type is allocated for this purpose
1128      * @return an array containing all of the elements in this deque
1129      * @throws ArrayStoreException if the runtime type of the specified array
1130      *         is not a supertype of the runtime type of every element in
1131      *         this deque
1132      * @throws NullPointerException if the specified array is null
1133      */
1134     @SuppressWarnings("unchecked")
toArray(T[] a)1135     public <T> T[] toArray(T[] a) {
1136         final int size;
1137         if ((size = size()) > a.length)
1138             return toArray((Class<T[]>) a.getClass());
1139         final Object[] es = elements;
1140         for (int i = head, j = 0, len = Math.min(size, es.length - i);
1141              ; i = 0, len = tail) {
1142             System.arraycopy(es, i, a, j, len);
1143             if ((j += len) == size) break;
1144         }
1145         if (size < a.length)
1146             a[size] = null;
1147         return a;
1148     }
1149 
1150     // *** Object methods ***
1151 
1152     /**
1153      * Returns a copy of this deque.
1154      *
1155      * @return a copy of this deque
1156      */
clone()1157     public ArrayDeque<E> clone() {
1158         try {
1159             @SuppressWarnings("unchecked")
1160             ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
1161             result.elements = Arrays.copyOf(elements, elements.length);
1162             return result;
1163         } catch (CloneNotSupportedException e) {
1164             throw new AssertionError();
1165         }
1166     }
1167 
1168     @java.io.Serial
1169     private static final long serialVersionUID = 2340985798034038923L;
1170 
1171     /**
1172      * Saves this deque to a stream (that is, serializes it).
1173      *
1174      * @param s the stream
1175      * @throws java.io.IOException if an I/O error occurs
1176      * @serialData The current size ({@code int}) of the deque,
1177      * followed by all of its elements (each an object reference) in
1178      * first-to-last order.
1179      */
1180     @java.io.Serial
writeObject(java.io.ObjectOutputStream s)1181     private void writeObject(java.io.ObjectOutputStream s)
1182             throws java.io.IOException {
1183         s.defaultWriteObject();
1184 
1185         // Write out size
1186         s.writeInt(size());
1187 
1188         // Write out elements in order.
1189         final Object[] es = elements;
1190         for (int i = head, end = tail, to = (i <= end) ? end : es.length;
1191              ; i = 0, to = end) {
1192             for (; i < to; i++)
1193                 s.writeObject(es[i]);
1194             if (to == end) break;
1195         }
1196     }
1197 
1198     /**
1199      * Reconstitutes this deque from a stream (that is, deserializes it).
1200      * @param s the stream
1201      * @throws ClassNotFoundException if the class of a serialized object
1202      *         could not be found
1203      * @throws java.io.IOException if an I/O error occurs
1204      */
1205     @java.io.Serial
readObject(java.io.ObjectInputStream s)1206     private void readObject(java.io.ObjectInputStream s)
1207             throws java.io.IOException, ClassNotFoundException {
1208         s.defaultReadObject();
1209 
1210         // Read in size and allocate array
1211         int size = s.readInt();
1212         SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, size + 1);
1213         elements = new Object[size + 1];
1214         this.tail = size;
1215 
1216         // Read in all elements in the proper order.
1217         for (int i = 0; i < size; i++)
1218             elements[i] = s.readObject();
1219     }
1220 
1221     /** debugging */
checkInvariants()1222     void checkInvariants() {
1223         // Use head and tail fields with empty slot at tail strategy.
1224         // head == tail disambiguates to "empty".
1225         try {
1226             int capacity = elements.length;
1227             // assert 0 <= head && head < capacity;
1228             // assert 0 <= tail && tail < capacity;
1229             // assert capacity > 0;
1230             // assert size() < capacity;
1231             // assert head == tail || elements[head] != null;
1232             // assert elements[tail] == null;
1233             // assert head == tail || elements[dec(tail, capacity)] != null;
1234         } catch (Throwable t) {
1235             System.err.printf("head=%d tail=%d capacity=%d%n",
1236                               head, tail, elements.length);
1237             System.err.printf("elements=%s%n",
1238                               Arrays.toString(elements));
1239             throw t;
1240         }
1241     }
1242 
1243 }
1244