emul/compact/src/main/java/java/util/ArrayDeque.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Mon, 28 Jan 2013 13:52:28 +0100
changeset 599 d0f57d3ea898
parent 597 ee8a922f4268
child 636 8d0be6a9a809
permissions -rw-r--r--
More java classes requested by FX guys
     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 import java.io.*;
    37 import org.apidesign.bck2brwsr.emul.lang.System;
    38 
    39 /**
    40  * Resizable-array implementation of the {@link Deque} interface.  Array
    41  * deques have no capacity restrictions; they grow as necessary to support
    42  * usage.  They are not thread-safe; in the absence of external
    43  * synchronization, they do not support concurrent access by multiple threads.
    44  * Null elements are prohibited.  This class is likely to be faster than
    45  * {@link Stack} when used as a stack, and faster than {@link LinkedList}
    46  * when used as a queue.
    47  *
    48  * <p>Most <tt>ArrayDeque</tt> operations run in amortized constant time.
    49  * Exceptions include {@link #remove(Object) remove}, {@link
    50  * #removeFirstOccurrence removeFirstOccurrence}, {@link #removeLastOccurrence
    51  * removeLastOccurrence}, {@link #contains contains}, {@link #iterator
    52  * iterator.remove()}, and the bulk operations, all of which run in linear
    53  * time.
    54  *
    55  * <p>The iterators returned by this class's <tt>iterator</tt> method are
    56  * <i>fail-fast</i>: If the deque is modified at any time after the iterator
    57  * is created, in any way except through the iterator's own <tt>remove</tt>
    58  * method, the iterator will generally throw a {@link
    59  * ConcurrentModificationException}.  Thus, in the face of concurrent
    60  * modification, the iterator fails quickly and cleanly, rather than risking
    61  * arbitrary, non-deterministic behavior at an undetermined time in the
    62  * future.
    63  *
    64  * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
    65  * as it is, generally speaking, impossible to make any hard guarantees in the
    66  * presence of unsynchronized concurrent modification.  Fail-fast iterators
    67  * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
    68  * Therefore, it would be wrong to write a program that depended on this
    69  * exception for its correctness: <i>the fail-fast behavior of iterators
    70  * should be used only to detect bugs.</i>
    71  *
    72  * <p>This class and its iterator implement all of the
    73  * <em>optional</em> methods of the {@link Collection} and {@link
    74  * Iterator} interfaces.
    75  *
    76  * <p>This class is a member of the
    77  * <a href="{@docRoot}/../technotes/guides/collections/index.html">
    78  * Java Collections Framework</a>.
    79  *
    80  * @author  Josh Bloch and Doug Lea
    81  * @since   1.6
    82  * @param <E> the type of elements held in this collection
    83  */
    84 public class ArrayDeque<E> extends AbstractCollection<E>
    85                            implements Deque<E>, Cloneable, Serializable
    86 {
    87     /**
    88      * The array in which the elements of the deque are stored.
    89      * The capacity of the deque is the length of this array, which is
    90      * always a power of two. The array is never allowed to become
    91      * full, except transiently within an addX method where it is
    92      * resized (see doubleCapacity) immediately upon becoming full,
    93      * thus avoiding head and tail wrapping around to equal each
    94      * other.  We also guarantee that all array cells not holding
    95      * deque elements are always null.
    96      */
    97     private transient E[] elements;
    98 
    99     /**
   100      * The index of the element at the head of the deque (which is the
   101      * element that would be removed by remove() or pop()); or an
   102      * arbitrary number equal to tail if the deque is empty.
   103      */
   104     private transient int head;
   105 
   106     /**
   107      * The index at which the next element would be added to the tail
   108      * of the deque (via addLast(E), add(E), or push(E)).
   109      */
   110     private transient int tail;
   111 
   112     /**
   113      * The minimum capacity that we'll use for a newly created deque.
   114      * Must be a power of 2.
   115      */
   116     private static final int MIN_INITIAL_CAPACITY = 8;
   117 
   118     // ******  Array allocation and resizing utilities ******
   119 
   120     /**
   121      * Allocate empty array to hold the given number of elements.
   122      *
   123      * @param numElements  the number of elements to hold
   124      */
   125     private void allocateElements(int numElements) {
   126         int initialCapacity = MIN_INITIAL_CAPACITY;
   127         // Find the best power of two to hold elements.
   128         // Tests "<=" because arrays aren't kept full.
   129         if (numElements >= initialCapacity) {
   130             initialCapacity = numElements;
   131             initialCapacity |= (initialCapacity >>>  1);
   132             initialCapacity |= (initialCapacity >>>  2);
   133             initialCapacity |= (initialCapacity >>>  4);
   134             initialCapacity |= (initialCapacity >>>  8);
   135             initialCapacity |= (initialCapacity >>> 16);
   136             initialCapacity++;
   137 
   138             if (initialCapacity < 0)   // Too many elements, must back off
   139                 initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
   140         }
   141         elements = (E[]) new Object[initialCapacity];
   142     }
   143 
   144     /**
   145      * Double the capacity of this deque.  Call only when full, i.e.,
   146      * when head and tail have wrapped around to become equal.
   147      */
   148     private void doubleCapacity() {
   149         assert head == tail;
   150         int p = head;
   151         int n = elements.length;
   152         int r = n - p; // number of elements to the right of p
   153         int newCapacity = n << 1;
   154         if (newCapacity < 0)
   155             throw new IllegalStateException("Sorry, deque too big");
   156         Object[] a = new Object[newCapacity];
   157         System.arraycopy(elements, p, a, 0, r);
   158         System.arraycopy(elements, 0, a, r, p);
   159         elements = (E[])a;
   160         head = 0;
   161         tail = n;
   162     }
   163 
   164     /**
   165      * Copies the elements from our element array into the specified array,
   166      * in order (from first to last element in the deque).  It is assumed
   167      * that the array is large enough to hold all elements in the deque.
   168      *
   169      * @return its argument
   170      */
   171     private <T> T[] copyElements(T[] a) {
   172         if (head < tail) {
   173             System.arraycopy(elements, head, a, 0, size());
   174         } else if (head > tail) {
   175             int headPortionLen = elements.length - head;
   176             System.arraycopy(elements, head, a, 0, headPortionLen);
   177             System.arraycopy(elements, 0, a, headPortionLen, tail);
   178         }
   179         return a;
   180     }
   181 
   182     /**
   183      * Constructs an empty array deque with an initial capacity
   184      * sufficient to hold 16 elements.
   185      */
   186     public ArrayDeque() {
   187         elements = (E[]) new Object[16];
   188     }
   189 
   190     /**
   191      * Constructs an empty array deque with an initial capacity
   192      * sufficient to hold the specified number of elements.
   193      *
   194      * @param numElements  lower bound on initial capacity of the deque
   195      */
   196     public ArrayDeque(int numElements) {
   197         allocateElements(numElements);
   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         allocateElements(c.size());
   212         addAll(c);
   213     }
   214 
   215     // The main insertion and extraction methods are addFirst,
   216     // addLast, pollFirst, pollLast. The other methods are defined in
   217     // terms of these.
   218 
   219     /**
   220      * Inserts the specified element at the front of this deque.
   221      *
   222      * @param e the element to add
   223      * @throws NullPointerException if the specified element is null
   224      */
   225     public void addFirst(E e) {
   226         if (e == null)
   227             throw new NullPointerException();
   228         elements[head = (head - 1) & (elements.length - 1)] = e;
   229         if (head == tail)
   230             doubleCapacity();
   231     }
   232 
   233     /**
   234      * Inserts the specified element at the end of this deque.
   235      *
   236      * <p>This method is equivalent to {@link #add}.
   237      *
   238      * @param e the element to add
   239      * @throws NullPointerException if the specified element is null
   240      */
   241     public void addLast(E e) {
   242         if (e == null)
   243             throw new NullPointerException();
   244         elements[tail] = e;
   245         if ( (tail = (tail + 1) & (elements.length - 1)) == head)
   246             doubleCapacity();
   247     }
   248 
   249     /**
   250      * Inserts the specified element at the front of this deque.
   251      *
   252      * @param e the element to add
   253      * @return <tt>true</tt> (as specified by {@link Deque#offerFirst})
   254      * @throws NullPointerException if the specified element is null
   255      */
   256     public boolean offerFirst(E e) {
   257         addFirst(e);
   258         return true;
   259     }
   260 
   261     /**
   262      * Inserts the specified element at the end of this deque.
   263      *
   264      * @param e the element to add
   265      * @return <tt>true</tt> (as specified by {@link Deque#offerLast})
   266      * @throws NullPointerException if the specified element is null
   267      */
   268     public boolean offerLast(E e) {
   269         addLast(e);
   270         return true;
   271     }
   272 
   273     /**
   274      * @throws NoSuchElementException {@inheritDoc}
   275      */
   276     public E removeFirst() {
   277         E x = pollFirst();
   278         if (x == null)
   279             throw new NoSuchElementException();
   280         return x;
   281     }
   282 
   283     /**
   284      * @throws NoSuchElementException {@inheritDoc}
   285      */
   286     public E removeLast() {
   287         E x = pollLast();
   288         if (x == null)
   289             throw new NoSuchElementException();
   290         return x;
   291     }
   292 
   293     public E pollFirst() {
   294         int h = head;
   295         E result = elements[h]; // Element is null if deque empty
   296         if (result == null)
   297             return null;
   298         elements[h] = null;     // Must null out slot
   299         head = (h + 1) & (elements.length - 1);
   300         return result;
   301     }
   302 
   303     public E pollLast() {
   304         int t = (tail - 1) & (elements.length - 1);
   305         E result = elements[t];
   306         if (result == null)
   307             return null;
   308         elements[t] = null;
   309         tail = t;
   310         return result;
   311     }
   312 
   313     /**
   314      * @throws NoSuchElementException {@inheritDoc}
   315      */
   316     public E getFirst() {
   317         E x = elements[head];
   318         if (x == null)
   319             throw new NoSuchElementException();
   320         return x;
   321     }
   322 
   323     /**
   324      * @throws NoSuchElementException {@inheritDoc}
   325      */
   326     public E getLast() {
   327         E x = elements[(tail - 1) & (elements.length - 1)];
   328         if (x == null)
   329             throw new NoSuchElementException();
   330         return x;
   331     }
   332 
   333     public E peekFirst() {
   334         return elements[head]; // elements[head] is null if deque empty
   335     }
   336 
   337     public E peekLast() {
   338         return elements[(tail - 1) & (elements.length - 1)];
   339     }
   340 
   341     /**
   342      * Removes the first occurrence of the specified element in this
   343      * deque (when traversing the deque from head to tail).
   344      * If the deque does not contain the element, it is unchanged.
   345      * More formally, removes the first element <tt>e</tt> such that
   346      * <tt>o.equals(e)</tt> (if such an element exists).
   347      * Returns <tt>true</tt> if this deque contained the specified element
   348      * (or equivalently, if this deque changed as a result of the call).
   349      *
   350      * @param o element to be removed from this deque, if present
   351      * @return <tt>true</tt> if the deque contained the specified element
   352      */
   353     public boolean removeFirstOccurrence(Object o) {
   354         if (o == null)
   355             return false;
   356         int mask = elements.length - 1;
   357         int i = head;
   358         E x;
   359         while ( (x = elements[i]) != null) {
   360             if (o.equals(x)) {
   361                 delete(i);
   362                 return true;
   363             }
   364             i = (i + 1) & mask;
   365         }
   366         return false;
   367     }
   368 
   369     /**
   370      * Removes the last occurrence of the specified element in this
   371      * deque (when traversing the deque from head to tail).
   372      * If the deque does not contain the element, it is unchanged.
   373      * More formally, removes the last element <tt>e</tt> such that
   374      * <tt>o.equals(e)</tt> (if such an element exists).
   375      * Returns <tt>true</tt> if this deque contained the specified element
   376      * (or equivalently, if this deque changed as a result of the call).
   377      *
   378      * @param o element to be removed from this deque, if present
   379      * @return <tt>true</tt> if the deque contained the specified element
   380      */
   381     public boolean removeLastOccurrence(Object o) {
   382         if (o == null)
   383             return false;
   384         int mask = elements.length - 1;
   385         int i = (tail - 1) & mask;
   386         E x;
   387         while ( (x = elements[i]) != null) {
   388             if (o.equals(x)) {
   389                 delete(i);
   390                 return true;
   391             }
   392             i = (i - 1) & mask;
   393         }
   394         return false;
   395     }
   396 
   397     // *** Queue methods ***
   398 
   399     /**
   400      * Inserts the specified element at the end of this deque.
   401      *
   402      * <p>This method is equivalent to {@link #addLast}.
   403      *
   404      * @param e the element to add
   405      * @return <tt>true</tt> (as specified by {@link Collection#add})
   406      * @throws NullPointerException if the specified element is null
   407      */
   408     public boolean add(E e) {
   409         addLast(e);
   410         return true;
   411     }
   412 
   413     /**
   414      * Inserts the specified element at the end of this deque.
   415      *
   416      * <p>This method is equivalent to {@link #offerLast}.
   417      *
   418      * @param e the element to add
   419      * @return <tt>true</tt> (as specified by {@link Queue#offer})
   420      * @throws NullPointerException if the specified element is null
   421      */
   422     public boolean offer(E e) {
   423         return offerLast(e);
   424     }
   425 
   426     /**
   427      * Retrieves and removes the head of the queue represented by this deque.
   428      *
   429      * This method differs from {@link #poll poll} only in that it throws an
   430      * exception if this deque is empty.
   431      *
   432      * <p>This method is equivalent to {@link #removeFirst}.
   433      *
   434      * @return the head of the queue represented by this deque
   435      * @throws NoSuchElementException {@inheritDoc}
   436      */
   437     public E remove() {
   438         return removeFirst();
   439     }
   440 
   441     /**
   442      * Retrieves and removes the head of the queue represented by this deque
   443      * (in other words, the first element of this deque), or returns
   444      * <tt>null</tt> if this deque is empty.
   445      *
   446      * <p>This method is equivalent to {@link #pollFirst}.
   447      *
   448      * @return the head of the queue represented by this deque, or
   449      *         <tt>null</tt> if this deque is empty
   450      */
   451     public E poll() {
   452         return pollFirst();
   453     }
   454 
   455     /**
   456      * Retrieves, but does not remove, the head of the queue represented by
   457      * this deque.  This method differs from {@link #peek peek} only in
   458      * that it throws an exception if this deque is empty.
   459      *
   460      * <p>This method is equivalent to {@link #getFirst}.
   461      *
   462      * @return the head of the queue represented by this deque
   463      * @throws NoSuchElementException {@inheritDoc}
   464      */
   465     public E element() {
   466         return getFirst();
   467     }
   468 
   469     /**
   470      * Retrieves, but does not remove, the head of the queue represented by
   471      * this deque, or returns <tt>null</tt> if this deque is empty.
   472      *
   473      * <p>This method is equivalent to {@link #peekFirst}.
   474      *
   475      * @return the head of the queue represented by this deque, or
   476      *         <tt>null</tt> if this deque is empty
   477      */
   478     public E peek() {
   479         return peekFirst();
   480     }
   481 
   482     // *** Stack methods ***
   483 
   484     /**
   485      * Pushes an element onto the stack represented by this deque.  In other
   486      * words, inserts the element at the front of this deque.
   487      *
   488      * <p>This method is equivalent to {@link #addFirst}.
   489      *
   490      * @param e the element to push
   491      * @throws NullPointerException if the specified element is null
   492      */
   493     public void push(E e) {
   494         addFirst(e);
   495     }
   496 
   497     /**
   498      * Pops an element from the stack represented by this deque.  In other
   499      * words, removes and returns the first element of this deque.
   500      *
   501      * <p>This method is equivalent to {@link #removeFirst()}.
   502      *
   503      * @return the element at the front of this deque (which is the top
   504      *         of the stack represented by this deque)
   505      * @throws NoSuchElementException {@inheritDoc}
   506      */
   507     public E pop() {
   508         return removeFirst();
   509     }
   510 
   511     private void checkInvariants() {
   512         assert elements[tail] == null;
   513         assert head == tail ? elements[head] == null :
   514             (elements[head] != null &&
   515              elements[(tail - 1) & (elements.length - 1)] != null);
   516         assert elements[(head - 1) & (elements.length - 1)] == null;
   517     }
   518 
   519     /**
   520      * Removes the element at the specified position in the elements array,
   521      * adjusting head and tail as necessary.  This can result in motion of
   522      * elements backwards or forwards in the array.
   523      *
   524      * <p>This method is called delete rather than remove to emphasize
   525      * that its semantics differ from those of {@link List#remove(int)}.
   526      *
   527      * @return true if elements moved backwards
   528      */
   529     private boolean delete(int i) {
   530         checkInvariants();
   531         final E[] elements = this.elements;
   532         final int mask = elements.length - 1;
   533         final int h = head;
   534         final int t = tail;
   535         final int front = (i - h) & mask;
   536         final int back  = (t - i) & mask;
   537 
   538         // Invariant: head <= i < tail mod circularity
   539         if (front >= ((t - h) & mask))
   540             throw new ConcurrentModificationException();
   541 
   542         // Optimize for least element motion
   543         if (front < back) {
   544             if (h <= i) {
   545                 System.arraycopy(elements, h, elements, h + 1, front);
   546             } else { // Wrap around
   547                 System.arraycopy(elements, 0, elements, 1, i);
   548                 elements[0] = elements[mask];
   549                 System.arraycopy(elements, h, elements, h + 1, mask - h);
   550             }
   551             elements[h] = null;
   552             head = (h + 1) & mask;
   553             return false;
   554         } else {
   555             if (i < t) { // Copy the null tail as well
   556                 System.arraycopy(elements, i + 1, elements, i, back);
   557                 tail = t - 1;
   558             } else { // Wrap around
   559                 System.arraycopy(elements, i + 1, elements, i, mask - i);
   560                 elements[mask] = elements[0];
   561                 System.arraycopy(elements, 1, elements, 0, t);
   562                 tail = (t - 1) & mask;
   563             }
   564             return true;
   565         }
   566     }
   567 
   568     // *** Collection Methods ***
   569 
   570     /**
   571      * Returns the number of elements in this deque.
   572      *
   573      * @return the number of elements in this deque
   574      */
   575     public int size() {
   576         return (tail - head) & (elements.length - 1);
   577     }
   578 
   579     /**
   580      * Returns <tt>true</tt> if this deque contains no elements.
   581      *
   582      * @return <tt>true</tt> if this deque contains no elements
   583      */
   584     public boolean isEmpty() {
   585         return head == tail;
   586     }
   587 
   588     /**
   589      * Returns an iterator over the elements in this deque.  The elements
   590      * will be ordered from first (head) to last (tail).  This is the same
   591      * order that elements would be dequeued (via successive calls to
   592      * {@link #remove} or popped (via successive calls to {@link #pop}).
   593      *
   594      * @return an iterator over the elements in this deque
   595      */
   596     public Iterator<E> iterator() {
   597         return new DeqIterator();
   598     }
   599 
   600     public Iterator<E> descendingIterator() {
   601         return new DescendingIterator();
   602     }
   603 
   604     private class DeqIterator implements Iterator<E> {
   605         /**
   606          * Index of element to be returned by subsequent call to next.
   607          */
   608         private int cursor = head;
   609 
   610         /**
   611          * Tail recorded at construction (also in remove), to stop
   612          * iterator and also to check for comodification.
   613          */
   614         private int fence = tail;
   615 
   616         /**
   617          * Index of element returned by most recent call to next.
   618          * Reset to -1 if element is deleted by a call to remove.
   619          */
   620         private int lastRet = -1;
   621 
   622         public boolean hasNext() {
   623             return cursor != fence;
   624         }
   625 
   626         public E next() {
   627             if (cursor == fence)
   628                 throw new NoSuchElementException();
   629             E result = elements[cursor];
   630             // This check doesn't catch all possible comodifications,
   631             // but does catch the ones that corrupt traversal
   632             if (tail != fence || result == null)
   633                 throw new ConcurrentModificationException();
   634             lastRet = cursor;
   635             cursor = (cursor + 1) & (elements.length - 1);
   636             return result;
   637         }
   638 
   639         public void remove() {
   640             if (lastRet < 0)
   641                 throw new IllegalStateException();
   642             if (delete(lastRet)) { // if left-shifted, undo increment in next()
   643                 cursor = (cursor - 1) & (elements.length - 1);
   644                 fence = tail;
   645             }
   646             lastRet = -1;
   647         }
   648     }
   649 
   650     private class DescendingIterator implements Iterator<E> {
   651         /*
   652          * This class is nearly a mirror-image of DeqIterator, using
   653          * tail instead of head for initial cursor, and head instead of
   654          * tail for fence.
   655          */
   656         private int cursor = tail;
   657         private int fence = head;
   658         private int lastRet = -1;
   659 
   660         public boolean hasNext() {
   661             return cursor != fence;
   662         }
   663 
   664         public E next() {
   665             if (cursor == fence)
   666                 throw new NoSuchElementException();
   667             cursor = (cursor - 1) & (elements.length - 1);
   668             E result = elements[cursor];
   669             if (head != fence || result == null)
   670                 throw new ConcurrentModificationException();
   671             lastRet = cursor;
   672             return result;
   673         }
   674 
   675         public void remove() {
   676             if (lastRet < 0)
   677                 throw new IllegalStateException();
   678             if (!delete(lastRet)) {
   679                 cursor = (cursor + 1) & (elements.length - 1);
   680                 fence = head;
   681             }
   682             lastRet = -1;
   683         }
   684     }
   685 
   686     /**
   687      * Returns <tt>true</tt> if this deque contains the specified element.
   688      * More formally, returns <tt>true</tt> if and only if this deque contains
   689      * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
   690      *
   691      * @param o object to be checked for containment in this deque
   692      * @return <tt>true</tt> if this deque contains the specified element
   693      */
   694     public boolean contains(Object o) {
   695         if (o == null)
   696             return false;
   697         int mask = elements.length - 1;
   698         int i = head;
   699         E x;
   700         while ( (x = elements[i]) != null) {
   701             if (o.equals(x))
   702                 return true;
   703             i = (i + 1) & mask;
   704         }
   705         return false;
   706     }
   707 
   708     /**
   709      * Removes a single instance of the specified element from this deque.
   710      * If the deque does not contain the element, it is unchanged.
   711      * More formally, removes the first element <tt>e</tt> such that
   712      * <tt>o.equals(e)</tt> (if such an element exists).
   713      * Returns <tt>true</tt> if this deque contained the specified element
   714      * (or equivalently, if this deque changed as a result of the call).
   715      *
   716      * <p>This method is equivalent to {@link #removeFirstOccurrence}.
   717      *
   718      * @param o element to be removed from this deque, if present
   719      * @return <tt>true</tt> if this deque contained the specified element
   720      */
   721     public boolean remove(Object o) {
   722         return removeFirstOccurrence(o);
   723     }
   724 
   725     /**
   726      * Removes all of the elements from this deque.
   727      * The deque will be empty after this call returns.
   728      */
   729     public void clear() {
   730         int h = head;
   731         int t = tail;
   732         if (h != t) { // clear all cells
   733             head = tail = 0;
   734             int i = h;
   735             int mask = elements.length - 1;
   736             do {
   737                 elements[i] = null;
   738                 i = (i + 1) & mask;
   739             } while (i != t);
   740         }
   741     }
   742 
   743     /**
   744      * Returns an array containing all of the elements in this deque
   745      * in proper sequence (from first to last element).
   746      *
   747      * <p>The returned array will be "safe" in that no references to it are
   748      * maintained by this deque.  (In other words, this method must allocate
   749      * a new array).  The caller is thus free to modify the returned array.
   750      *
   751      * <p>This method acts as bridge between array-based and collection-based
   752      * APIs.
   753      *
   754      * @return an array containing all of the elements in this deque
   755      */
   756     public Object[] toArray() {
   757         return copyElements(new Object[size()]);
   758     }
   759 
   760     /**
   761      * Returns an array containing all of the elements in this deque in
   762      * proper sequence (from first to last element); the runtime type of the
   763      * returned array is that of the specified array.  If the deque fits in
   764      * the specified array, it is returned therein.  Otherwise, a new array
   765      * is allocated with the runtime type of the specified array and the
   766      * size of this deque.
   767      *
   768      * <p>If this deque fits in the specified array with room to spare
   769      * (i.e., the array has more elements than this deque), the element in
   770      * the array immediately following the end of the deque is set to
   771      * <tt>null</tt>.
   772      *
   773      * <p>Like the {@link #toArray()} method, this method acts as bridge between
   774      * array-based and collection-based APIs.  Further, this method allows
   775      * precise control over the runtime type of the output array, and may,
   776      * under certain circumstances, be used to save allocation costs.
   777      *
   778      * <p>Suppose <tt>x</tt> is a deque known to contain only strings.
   779      * The following code can be used to dump the deque into a newly
   780      * allocated array of <tt>String</tt>:
   781      *
   782      * <pre>
   783      *     String[] y = x.toArray(new String[0]);</pre>
   784      *
   785      * Note that <tt>toArray(new Object[0])</tt> is identical in function to
   786      * <tt>toArray()</tt>.
   787      *
   788      * @param a the array into which the elements of the deque are to
   789      *          be stored, if it is big enough; otherwise, a new array of the
   790      *          same runtime type is allocated for this purpose
   791      * @return an array containing all of the elements in this deque
   792      * @throws ArrayStoreException if the runtime type of the specified array
   793      *         is not a supertype of the runtime type of every element in
   794      *         this deque
   795      * @throws NullPointerException if the specified array is null
   796      */
   797     public <T> T[] toArray(T[] a) {
   798         int size = size();
   799         if (a.length < size)
   800             a = (T[])java.lang.reflect.Array.newInstance(
   801                     a.getClass().getComponentType(), size);
   802         copyElements(a);
   803         if (a.length > size)
   804             a[size] = null;
   805         return a;
   806     }
   807 
   808     // *** Object methods ***
   809 
   810     /**
   811      * Returns a copy of this deque.
   812      *
   813      * @return a copy of this deque
   814      */
   815     public ArrayDeque<E> clone() {
   816         try {
   817             ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
   818             result.elements = Arrays.copyOf(elements, elements.length);
   819             return result;
   820 
   821         } catch (CloneNotSupportedException e) {
   822             throw new AssertionError();
   823         }
   824     }
   825 
   826     /**
   827      * Appease the serialization gods.
   828      */
   829     private static final long serialVersionUID = 2340985798034038923L;
   830 
   831 }