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