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