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