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