emul/compact/src/main/java/java/util/PriorityQueue.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 01 Feb 2013 16:10:10 +0100
branchjdk7-b147
changeset 633 bc6f3be91306
child 635 e5cc7edead25
permissions -rw-r--r--
More classes needed by David
jaroslav@633
     1
/*
jaroslav@633
     2
 * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
jaroslav@633
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@633
     4
 *
jaroslav@633
     5
 * This code is free software; you can redistribute it and/or modify it
jaroslav@633
     6
 * under the terms of the GNU General Public License version 2 only, as
jaroslav@633
     7
 * published by the Free Software Foundation.  Oracle designates this
jaroslav@633
     8
 * particular file as subject to the "Classpath" exception as provided
jaroslav@633
     9
 * by Oracle in the LICENSE file that accompanied this code.
jaroslav@633
    10
 *
jaroslav@633
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@633
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@633
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jaroslav@633
    14
 * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@633
    15
 * accompanied this code).
jaroslav@633
    16
 *
jaroslav@633
    17
 * You should have received a copy of the GNU General Public License version
jaroslav@633
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@633
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@633
    20
 *
jaroslav@633
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@633
    22
 * or visit www.oracle.com if you need additional information or have any
jaroslav@633
    23
 * questions.
jaroslav@633
    24
 */
jaroslav@633
    25
jaroslav@633
    26
package java.util;
jaroslav@633
    27
jaroslav@633
    28
/**
jaroslav@633
    29
 * An unbounded priority {@linkplain Queue queue} based on a priority heap.
jaroslav@633
    30
 * The elements of the priority queue are ordered according to their
jaroslav@633
    31
 * {@linkplain Comparable natural ordering}, or by a {@link Comparator}
jaroslav@633
    32
 * provided at queue construction time, depending on which constructor is
jaroslav@633
    33
 * used.  A priority queue does not permit {@code null} elements.
jaroslav@633
    34
 * A priority queue relying on natural ordering also does not permit
jaroslav@633
    35
 * insertion of non-comparable objects (doing so may result in
jaroslav@633
    36
 * {@code ClassCastException}).
jaroslav@633
    37
 *
jaroslav@633
    38
 * <p>The <em>head</em> of this queue is the <em>least</em> element
jaroslav@633
    39
 * with respect to the specified ordering.  If multiple elements are
jaroslav@633
    40
 * tied for least value, the head is one of those elements -- ties are
jaroslav@633
    41
 * broken arbitrarily.  The queue retrieval operations {@code poll},
jaroslav@633
    42
 * {@code remove}, {@code peek}, and {@code element} access the
jaroslav@633
    43
 * element at the head of the queue.
jaroslav@633
    44
 *
jaroslav@633
    45
 * <p>A priority queue is unbounded, but has an internal
jaroslav@633
    46
 * <i>capacity</i> governing the size of an array used to store the
jaroslav@633
    47
 * elements on the queue.  It is always at least as large as the queue
jaroslav@633
    48
 * size.  As elements are added to a priority queue, its capacity
jaroslav@633
    49
 * grows automatically.  The details of the growth policy are not
jaroslav@633
    50
 * specified.
jaroslav@633
    51
 *
jaroslav@633
    52
 * <p>This class and its iterator implement all of the
jaroslav@633
    53
 * <em>optional</em> methods of the {@link Collection} and {@link
jaroslav@633
    54
 * Iterator} interfaces.  The Iterator provided in method {@link
jaroslav@633
    55
 * #iterator()} is <em>not</em> guaranteed to traverse the elements of
jaroslav@633
    56
 * the priority queue in any particular order. If you need ordered
jaroslav@633
    57
 * traversal, consider using {@code Arrays.sort(pq.toArray())}.
jaroslav@633
    58
 *
jaroslav@633
    59
 * <p> <strong>Note that this implementation is not synchronized.</strong>
jaroslav@633
    60
 * Multiple threads should not access a {@code PriorityQueue}
jaroslav@633
    61
 * instance concurrently if any of the threads modifies the queue.
jaroslav@633
    62
 * Instead, use the thread-safe {@link
jaroslav@633
    63
 * java.util.concurrent.PriorityBlockingQueue} class.
jaroslav@633
    64
 *
jaroslav@633
    65
 * <p>Implementation note: this implementation provides
jaroslav@633
    66
 * O(log(n)) time for the enqueing and dequeing methods
jaroslav@633
    67
 * ({@code offer}, {@code poll}, {@code remove()} and {@code add});
jaroslav@633
    68
 * linear time for the {@code remove(Object)} and {@code contains(Object)}
jaroslav@633
    69
 * methods; and constant time for the retrieval methods
jaroslav@633
    70
 * ({@code peek}, {@code element}, and {@code size}).
jaroslav@633
    71
 *
jaroslav@633
    72
 * <p>This class is a member of the
jaroslav@633
    73
 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
jaroslav@633
    74
 * Java Collections Framework</a>.
jaroslav@633
    75
 *
jaroslav@633
    76
 * @since 1.5
jaroslav@633
    77
 * @author Josh Bloch, Doug Lea
jaroslav@633
    78
 * @param <E> the type of elements held in this collection
jaroslav@633
    79
 */
jaroslav@633
    80
public class PriorityQueue<E> extends AbstractQueue<E>
jaroslav@633
    81
    implements java.io.Serializable {
jaroslav@633
    82
jaroslav@633
    83
    private static final long serialVersionUID = -7720805057305804111L;
jaroslav@633
    84
jaroslav@633
    85
    private static final int DEFAULT_INITIAL_CAPACITY = 11;
jaroslav@633
    86
jaroslav@633
    87
    /**
jaroslav@633
    88
     * Priority queue represented as a balanced binary heap: the two
jaroslav@633
    89
     * children of queue[n] are queue[2*n+1] and queue[2*(n+1)].  The
jaroslav@633
    90
     * priority queue is ordered by comparator, or by the elements'
jaroslav@633
    91
     * natural ordering, if comparator is null: For each node n in the
jaroslav@633
    92
     * heap and each descendant d of n, n <= d.  The element with the
jaroslav@633
    93
     * lowest value is in queue[0], assuming the queue is nonempty.
jaroslav@633
    94
     */
jaroslav@633
    95
    private transient Object[] queue;
jaroslav@633
    96
jaroslav@633
    97
    /**
jaroslav@633
    98
     * The number of elements in the priority queue.
jaroslav@633
    99
     */
jaroslav@633
   100
    private int size = 0;
jaroslav@633
   101
jaroslav@633
   102
    /**
jaroslav@633
   103
     * The comparator, or null if priority queue uses elements'
jaroslav@633
   104
     * natural ordering.
jaroslav@633
   105
     */
jaroslav@633
   106
    private final Comparator<? super E> comparator;
jaroslav@633
   107
jaroslav@633
   108
    /**
jaroslav@633
   109
     * The number of times this priority queue has been
jaroslav@633
   110
     * <i>structurally modified</i>.  See AbstractList for gory details.
jaroslav@633
   111
     */
jaroslav@633
   112
    private transient int modCount = 0;
jaroslav@633
   113
jaroslav@633
   114
    /**
jaroslav@633
   115
     * Creates a {@code PriorityQueue} with the default initial
jaroslav@633
   116
     * capacity (11) that orders its elements according to their
jaroslav@633
   117
     * {@linkplain Comparable natural ordering}.
jaroslav@633
   118
     */
jaroslav@633
   119
    public PriorityQueue() {
jaroslav@633
   120
        this(DEFAULT_INITIAL_CAPACITY, null);
jaroslav@633
   121
    }
jaroslav@633
   122
jaroslav@633
   123
    /**
jaroslav@633
   124
     * Creates a {@code PriorityQueue} with the specified initial
jaroslav@633
   125
     * capacity that orders its elements according to their
jaroslav@633
   126
     * {@linkplain Comparable natural ordering}.
jaroslav@633
   127
     *
jaroslav@633
   128
     * @param initialCapacity the initial capacity for this priority queue
jaroslav@633
   129
     * @throws IllegalArgumentException if {@code initialCapacity} is less
jaroslav@633
   130
     *         than 1
jaroslav@633
   131
     */
jaroslav@633
   132
    public PriorityQueue(int initialCapacity) {
jaroslav@633
   133
        this(initialCapacity, null);
jaroslav@633
   134
    }
jaroslav@633
   135
jaroslav@633
   136
    /**
jaroslav@633
   137
     * Creates a {@code PriorityQueue} with the specified initial capacity
jaroslav@633
   138
     * that orders its elements according to the specified comparator.
jaroslav@633
   139
     *
jaroslav@633
   140
     * @param  initialCapacity the initial capacity for this priority queue
jaroslav@633
   141
     * @param  comparator the comparator that will be used to order this
jaroslav@633
   142
     *         priority queue.  If {@code null}, the {@linkplain Comparable
jaroslav@633
   143
     *         natural ordering} of the elements will be used.
jaroslav@633
   144
     * @throws IllegalArgumentException if {@code initialCapacity} is
jaroslav@633
   145
     *         less than 1
jaroslav@633
   146
     */
jaroslav@633
   147
    public PriorityQueue(int initialCapacity,
jaroslav@633
   148
                         Comparator<? super E> comparator) {
jaroslav@633
   149
        // Note: This restriction of at least one is not actually needed,
jaroslav@633
   150
        // but continues for 1.5 compatibility
jaroslav@633
   151
        if (initialCapacity < 1)
jaroslav@633
   152
            throw new IllegalArgumentException();
jaroslav@633
   153
        this.queue = new Object[initialCapacity];
jaroslav@633
   154
        this.comparator = comparator;
jaroslav@633
   155
    }
jaroslav@633
   156
jaroslav@633
   157
    /**
jaroslav@633
   158
     * Creates a {@code PriorityQueue} containing the elements in the
jaroslav@633
   159
     * specified collection.  If the specified collection is an instance of
jaroslav@633
   160
     * a {@link SortedSet} or is another {@code PriorityQueue}, this
jaroslav@633
   161
     * priority queue will be ordered according to the same ordering.
jaroslav@633
   162
     * Otherwise, this priority queue will be ordered according to the
jaroslav@633
   163
     * {@linkplain Comparable natural ordering} of its elements.
jaroslav@633
   164
     *
jaroslav@633
   165
     * @param  c the collection whose elements are to be placed
jaroslav@633
   166
     *         into this priority queue
jaroslav@633
   167
     * @throws ClassCastException if elements of the specified collection
jaroslav@633
   168
     *         cannot be compared to one another according to the priority
jaroslav@633
   169
     *         queue's ordering
jaroslav@633
   170
     * @throws NullPointerException if the specified collection or any
jaroslav@633
   171
     *         of its elements are null
jaroslav@633
   172
     */
jaroslav@633
   173
    @SuppressWarnings("unchecked")
jaroslav@633
   174
    public PriorityQueue(Collection<? extends E> c) {
jaroslav@633
   175
        if (c instanceof SortedSet<?>) {
jaroslav@633
   176
            SortedSet<? extends E> ss = (SortedSet<? extends E>) c;
jaroslav@633
   177
            this.comparator = (Comparator<? super E>) ss.comparator();
jaroslav@633
   178
            initElementsFromCollection(ss);
jaroslav@633
   179
        }
jaroslav@633
   180
        else if (c instanceof PriorityQueue<?>) {
jaroslav@633
   181
            PriorityQueue<? extends E> pq = (PriorityQueue<? extends E>) c;
jaroslav@633
   182
            this.comparator = (Comparator<? super E>) pq.comparator();
jaroslav@633
   183
            initFromPriorityQueue(pq);
jaroslav@633
   184
        }
jaroslav@633
   185
        else {
jaroslav@633
   186
            this.comparator = null;
jaroslav@633
   187
            initFromCollection(c);
jaroslav@633
   188
        }
jaroslav@633
   189
    }
jaroslav@633
   190
jaroslav@633
   191
    /**
jaroslav@633
   192
     * Creates a {@code PriorityQueue} containing the elements in the
jaroslav@633
   193
     * specified priority queue.  This priority queue will be
jaroslav@633
   194
     * ordered according to the same ordering as the given priority
jaroslav@633
   195
     * queue.
jaroslav@633
   196
     *
jaroslav@633
   197
     * @param  c the priority queue whose elements are to be placed
jaroslav@633
   198
     *         into this priority queue
jaroslav@633
   199
     * @throws ClassCastException if elements of {@code c} cannot be
jaroslav@633
   200
     *         compared to one another according to {@code c}'s
jaroslav@633
   201
     *         ordering
jaroslav@633
   202
     * @throws NullPointerException if the specified priority queue or any
jaroslav@633
   203
     *         of its elements are null
jaroslav@633
   204
     */
jaroslav@633
   205
    @SuppressWarnings("unchecked")
jaroslav@633
   206
    public PriorityQueue(PriorityQueue<? extends E> c) {
jaroslav@633
   207
        this.comparator = (Comparator<? super E>) c.comparator();
jaroslav@633
   208
        initFromPriorityQueue(c);
jaroslav@633
   209
    }
jaroslav@633
   210
jaroslav@633
   211
    /**
jaroslav@633
   212
     * Creates a {@code PriorityQueue} containing the elements in the
jaroslav@633
   213
     * specified sorted set.   This priority queue will be ordered
jaroslav@633
   214
     * according to the same ordering as the given sorted set.
jaroslav@633
   215
     *
jaroslav@633
   216
     * @param  c the sorted set whose elements are to be placed
jaroslav@633
   217
     *         into this priority queue
jaroslav@633
   218
     * @throws ClassCastException if elements of the specified sorted
jaroslav@633
   219
     *         set cannot be compared to one another according to the
jaroslav@633
   220
     *         sorted set's ordering
jaroslav@633
   221
     * @throws NullPointerException if the specified sorted set or any
jaroslav@633
   222
     *         of its elements are null
jaroslav@633
   223
     */
jaroslav@633
   224
    @SuppressWarnings("unchecked")
jaroslav@633
   225
    public PriorityQueue(SortedSet<? extends E> c) {
jaroslav@633
   226
        this.comparator = (Comparator<? super E>) c.comparator();
jaroslav@633
   227
        initElementsFromCollection(c);
jaroslav@633
   228
    }
jaroslav@633
   229
jaroslav@633
   230
    private void initFromPriorityQueue(PriorityQueue<? extends E> c) {
jaroslav@633
   231
        if (c.getClass() == PriorityQueue.class) {
jaroslav@633
   232
            this.queue = c.toArray();
jaroslav@633
   233
            this.size = c.size();
jaroslav@633
   234
        } else {
jaroslav@633
   235
            initFromCollection(c);
jaroslav@633
   236
        }
jaroslav@633
   237
    }
jaroslav@633
   238
jaroslav@633
   239
    private void initElementsFromCollection(Collection<? extends E> c) {
jaroslav@633
   240
        Object[] a = c.toArray();
jaroslav@633
   241
        // If c.toArray incorrectly doesn't return Object[], copy it.
jaroslav@633
   242
        if (a.getClass() != Object[].class)
jaroslav@633
   243
            a = Arrays.copyOf(a, a.length, Object[].class);
jaroslav@633
   244
        int len = a.length;
jaroslav@633
   245
        if (len == 1 || this.comparator != null)
jaroslav@633
   246
            for (int i = 0; i < len; i++)
jaroslav@633
   247
                if (a[i] == null)
jaroslav@633
   248
                    throw new NullPointerException();
jaroslav@633
   249
        this.queue = a;
jaroslav@633
   250
        this.size = a.length;
jaroslav@633
   251
    }
jaroslav@633
   252
jaroslav@633
   253
    /**
jaroslav@633
   254
     * Initializes queue array with elements from the given Collection.
jaroslav@633
   255
     *
jaroslav@633
   256
     * @param c the collection
jaroslav@633
   257
     */
jaroslav@633
   258
    private void initFromCollection(Collection<? extends E> c) {
jaroslav@633
   259
        initElementsFromCollection(c);
jaroslav@633
   260
        heapify();
jaroslav@633
   261
    }
jaroslav@633
   262
jaroslav@633
   263
    /**
jaroslav@633
   264
     * The maximum size of array to allocate.
jaroslav@633
   265
     * Some VMs reserve some header words in an array.
jaroslav@633
   266
     * Attempts to allocate larger arrays may result in
jaroslav@633
   267
     * OutOfMemoryError: Requested array size exceeds VM limit
jaroslav@633
   268
     */
jaroslav@633
   269
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
jaroslav@633
   270
jaroslav@633
   271
    /**
jaroslav@633
   272
     * Increases the capacity of the array.
jaroslav@633
   273
     *
jaroslav@633
   274
     * @param minCapacity the desired minimum capacity
jaroslav@633
   275
     */
jaroslav@633
   276
    private void grow(int minCapacity) {
jaroslav@633
   277
        int oldCapacity = queue.length;
jaroslav@633
   278
        // Double size if small; else grow by 50%
jaroslav@633
   279
        int newCapacity = oldCapacity + ((oldCapacity < 64) ?
jaroslav@633
   280
                                         (oldCapacity + 2) :
jaroslav@633
   281
                                         (oldCapacity >> 1));
jaroslav@633
   282
        // overflow-conscious code
jaroslav@633
   283
        if (newCapacity - MAX_ARRAY_SIZE > 0)
jaroslav@633
   284
            newCapacity = hugeCapacity(minCapacity);
jaroslav@633
   285
        queue = Arrays.copyOf(queue, newCapacity);
jaroslav@633
   286
    }
jaroslav@633
   287
jaroslav@633
   288
    private static int hugeCapacity(int minCapacity) {
jaroslav@633
   289
        if (minCapacity < 0) // overflow
jaroslav@633
   290
            throw new OutOfMemoryError();
jaroslav@633
   291
        return (minCapacity > MAX_ARRAY_SIZE) ?
jaroslav@633
   292
            Integer.MAX_VALUE :
jaroslav@633
   293
            MAX_ARRAY_SIZE;
jaroslav@633
   294
    }
jaroslav@633
   295
jaroslav@633
   296
    /**
jaroslav@633
   297
     * Inserts the specified element into this priority queue.
jaroslav@633
   298
     *
jaroslav@633
   299
     * @return {@code true} (as specified by {@link Collection#add})
jaroslav@633
   300
     * @throws ClassCastException if the specified element cannot be
jaroslav@633
   301
     *         compared with elements currently in this priority queue
jaroslav@633
   302
     *         according to the priority queue's ordering
jaroslav@633
   303
     * @throws NullPointerException if the specified element is null
jaroslav@633
   304
     */
jaroslav@633
   305
    public boolean add(E e) {
jaroslav@633
   306
        return offer(e);
jaroslav@633
   307
    }
jaroslav@633
   308
jaroslav@633
   309
    /**
jaroslav@633
   310
     * Inserts the specified element into this priority queue.
jaroslav@633
   311
     *
jaroslav@633
   312
     * @return {@code true} (as specified by {@link Queue#offer})
jaroslav@633
   313
     * @throws ClassCastException if the specified element cannot be
jaroslav@633
   314
     *         compared with elements currently in this priority queue
jaroslav@633
   315
     *         according to the priority queue's ordering
jaroslav@633
   316
     * @throws NullPointerException if the specified element is null
jaroslav@633
   317
     */
jaroslav@633
   318
    public boolean offer(E e) {
jaroslav@633
   319
        if (e == null)
jaroslav@633
   320
            throw new NullPointerException();
jaroslav@633
   321
        modCount++;
jaroslav@633
   322
        int i = size;
jaroslav@633
   323
        if (i >= queue.length)
jaroslav@633
   324
            grow(i + 1);
jaroslav@633
   325
        size = i + 1;
jaroslav@633
   326
        if (i == 0)
jaroslav@633
   327
            queue[0] = e;
jaroslav@633
   328
        else
jaroslav@633
   329
            siftUp(i, e);
jaroslav@633
   330
        return true;
jaroslav@633
   331
    }
jaroslav@633
   332
jaroslav@633
   333
    public E peek() {
jaroslav@633
   334
        if (size == 0)
jaroslav@633
   335
            return null;
jaroslav@633
   336
        return (E) queue[0];
jaroslav@633
   337
    }
jaroslav@633
   338
jaroslav@633
   339
    private int indexOf(Object o) {
jaroslav@633
   340
        if (o != null) {
jaroslav@633
   341
            for (int i = 0; i < size; i++)
jaroslav@633
   342
                if (o.equals(queue[i]))
jaroslav@633
   343
                    return i;
jaroslav@633
   344
        }
jaroslav@633
   345
        return -1;
jaroslav@633
   346
    }
jaroslav@633
   347
jaroslav@633
   348
    /**
jaroslav@633
   349
     * Removes a single instance of the specified element from this queue,
jaroslav@633
   350
     * if it is present.  More formally, removes an element {@code e} such
jaroslav@633
   351
     * that {@code o.equals(e)}, if this queue contains one or more such
jaroslav@633
   352
     * elements.  Returns {@code true} if and only if this queue contained
jaroslav@633
   353
     * the specified element (or equivalently, if this queue changed as a
jaroslav@633
   354
     * result of the call).
jaroslav@633
   355
     *
jaroslav@633
   356
     * @param o element to be removed from this queue, if present
jaroslav@633
   357
     * @return {@code true} if this queue changed as a result of the call
jaroslav@633
   358
     */
jaroslav@633
   359
    public boolean remove(Object o) {
jaroslav@633
   360
        int i = indexOf(o);
jaroslav@633
   361
        if (i == -1)
jaroslav@633
   362
            return false;
jaroslav@633
   363
        else {
jaroslav@633
   364
            removeAt(i);
jaroslav@633
   365
            return true;
jaroslav@633
   366
        }
jaroslav@633
   367
    }
jaroslav@633
   368
jaroslav@633
   369
    /**
jaroslav@633
   370
     * Version of remove using reference equality, not equals.
jaroslav@633
   371
     * Needed by iterator.remove.
jaroslav@633
   372
     *
jaroslav@633
   373
     * @param o element to be removed from this queue, if present
jaroslav@633
   374
     * @return {@code true} if removed
jaroslav@633
   375
     */
jaroslav@633
   376
    boolean removeEq(Object o) {
jaroslav@633
   377
        for (int i = 0; i < size; i++) {
jaroslav@633
   378
            if (o == queue[i]) {
jaroslav@633
   379
                removeAt(i);
jaroslav@633
   380
                return true;
jaroslav@633
   381
            }
jaroslav@633
   382
        }
jaroslav@633
   383
        return false;
jaroslav@633
   384
    }
jaroslav@633
   385
jaroslav@633
   386
    /**
jaroslav@633
   387
     * Returns {@code true} if this queue contains the specified element.
jaroslav@633
   388
     * More formally, returns {@code true} if and only if this queue contains
jaroslav@633
   389
     * at least one element {@code e} such that {@code o.equals(e)}.
jaroslav@633
   390
     *
jaroslav@633
   391
     * @param o object to be checked for containment in this queue
jaroslav@633
   392
     * @return {@code true} if this queue contains the specified element
jaroslav@633
   393
     */
jaroslav@633
   394
    public boolean contains(Object o) {
jaroslav@633
   395
        return indexOf(o) != -1;
jaroslav@633
   396
    }
jaroslav@633
   397
jaroslav@633
   398
    /**
jaroslav@633
   399
     * Returns an array containing all of the elements in this queue.
jaroslav@633
   400
     * The elements are in no particular order.
jaroslav@633
   401
     *
jaroslav@633
   402
     * <p>The returned array will be "safe" in that no references to it are
jaroslav@633
   403
     * maintained by this queue.  (In other words, this method must allocate
jaroslav@633
   404
     * a new array).  The caller is thus free to modify the returned array.
jaroslav@633
   405
     *
jaroslav@633
   406
     * <p>This method acts as bridge between array-based and collection-based
jaroslav@633
   407
     * APIs.
jaroslav@633
   408
     *
jaroslav@633
   409
     * @return an array containing all of the elements in this queue
jaroslav@633
   410
     */
jaroslav@633
   411
    public Object[] toArray() {
jaroslav@633
   412
        return Arrays.copyOf(queue, size);
jaroslav@633
   413
    }
jaroslav@633
   414
jaroslav@633
   415
    /**
jaroslav@633
   416
     * Returns an array containing all of the elements in this queue; the
jaroslav@633
   417
     * runtime type of the returned array is that of the specified array.
jaroslav@633
   418
     * The returned array elements are in no particular order.
jaroslav@633
   419
     * If the queue fits in the specified array, it is returned therein.
jaroslav@633
   420
     * Otherwise, a new array is allocated with the runtime type of the
jaroslav@633
   421
     * specified array and the size of this queue.
jaroslav@633
   422
     *
jaroslav@633
   423
     * <p>If the queue fits in the specified array with room to spare
jaroslav@633
   424
     * (i.e., the array has more elements than the queue), the element in
jaroslav@633
   425
     * the array immediately following the end of the collection is set to
jaroslav@633
   426
     * {@code null}.
jaroslav@633
   427
     *
jaroslav@633
   428
     * <p>Like the {@link #toArray()} method, this method acts as bridge between
jaroslav@633
   429
     * array-based and collection-based APIs.  Further, this method allows
jaroslav@633
   430
     * precise control over the runtime type of the output array, and may,
jaroslav@633
   431
     * under certain circumstances, be used to save allocation costs.
jaroslav@633
   432
     *
jaroslav@633
   433
     * <p>Suppose <tt>x</tt> is a queue known to contain only strings.
jaroslav@633
   434
     * The following code can be used to dump the queue into a newly
jaroslav@633
   435
     * allocated array of <tt>String</tt>:
jaroslav@633
   436
     *
jaroslav@633
   437
     * <pre>
jaroslav@633
   438
     *     String[] y = x.toArray(new String[0]);</pre>
jaroslav@633
   439
     *
jaroslav@633
   440
     * Note that <tt>toArray(new Object[0])</tt> is identical in function to
jaroslav@633
   441
     * <tt>toArray()</tt>.
jaroslav@633
   442
     *
jaroslav@633
   443
     * @param a the array into which the elements of the queue are to
jaroslav@633
   444
     *          be stored, if it is big enough; otherwise, a new array of the
jaroslav@633
   445
     *          same runtime type is allocated for this purpose.
jaroslav@633
   446
     * @return an array containing all of the elements in this queue
jaroslav@633
   447
     * @throws ArrayStoreException if the runtime type of the specified array
jaroslav@633
   448
     *         is not a supertype of the runtime type of every element in
jaroslav@633
   449
     *         this queue
jaroslav@633
   450
     * @throws NullPointerException if the specified array is null
jaroslav@633
   451
     */
jaroslav@633
   452
    public <T> T[] toArray(T[] a) {
jaroslav@633
   453
        if (a.length < size)
jaroslav@633
   454
            // Make a new array of a's runtime type, but my contents:
jaroslav@633
   455
            return (T[]) Arrays.copyOf(queue, size, a.getClass());
jaroslav@633
   456
        System.arraycopy(queue, 0, a, 0, size);
jaroslav@633
   457
        if (a.length > size)
jaroslav@633
   458
            a[size] = null;
jaroslav@633
   459
        return a;
jaroslav@633
   460
    }
jaroslav@633
   461
jaroslav@633
   462
    /**
jaroslav@633
   463
     * Returns an iterator over the elements in this queue. The iterator
jaroslav@633
   464
     * does not return the elements in any particular order.
jaroslav@633
   465
     *
jaroslav@633
   466
     * @return an iterator over the elements in this queue
jaroslav@633
   467
     */
jaroslav@633
   468
    public Iterator<E> iterator() {
jaroslav@633
   469
        return new Itr();
jaroslav@633
   470
    }
jaroslav@633
   471
jaroslav@633
   472
    private final class Itr implements Iterator<E> {
jaroslav@633
   473
        /**
jaroslav@633
   474
         * Index (into queue array) of element to be returned by
jaroslav@633
   475
         * subsequent call to next.
jaroslav@633
   476
         */
jaroslav@633
   477
        private int cursor = 0;
jaroslav@633
   478
jaroslav@633
   479
        /**
jaroslav@633
   480
         * Index of element returned by most recent call to next,
jaroslav@633
   481
         * unless that element came from the forgetMeNot list.
jaroslav@633
   482
         * Set to -1 if element is deleted by a call to remove.
jaroslav@633
   483
         */
jaroslav@633
   484
        private int lastRet = -1;
jaroslav@633
   485
jaroslav@633
   486
        /**
jaroslav@633
   487
         * A queue of elements that were moved from the unvisited portion of
jaroslav@633
   488
         * the heap into the visited portion as a result of "unlucky" element
jaroslav@633
   489
         * removals during the iteration.  (Unlucky element removals are those
jaroslav@633
   490
         * that require a siftup instead of a siftdown.)  We must visit all of
jaroslav@633
   491
         * the elements in this list to complete the iteration.  We do this
jaroslav@633
   492
         * after we've completed the "normal" iteration.
jaroslav@633
   493
         *
jaroslav@633
   494
         * We expect that most iterations, even those involving removals,
jaroslav@633
   495
         * will not need to store elements in this field.
jaroslav@633
   496
         */
jaroslav@633
   497
        private ArrayDeque<E> forgetMeNot = null;
jaroslav@633
   498
jaroslav@633
   499
        /**
jaroslav@633
   500
         * Element returned by the most recent call to next iff that
jaroslav@633
   501
         * element was drawn from the forgetMeNot list.
jaroslav@633
   502
         */
jaroslav@633
   503
        private E lastRetElt = null;
jaroslav@633
   504
jaroslav@633
   505
        /**
jaroslav@633
   506
         * The modCount value that the iterator believes that the backing
jaroslav@633
   507
         * Queue should have.  If this expectation is violated, the iterator
jaroslav@633
   508
         * has detected concurrent modification.
jaroslav@633
   509
         */
jaroslav@633
   510
        private int expectedModCount = modCount;
jaroslav@633
   511
jaroslav@633
   512
        public boolean hasNext() {
jaroslav@633
   513
            return cursor < size ||
jaroslav@633
   514
                (forgetMeNot != null && !forgetMeNot.isEmpty());
jaroslav@633
   515
        }
jaroslav@633
   516
jaroslav@633
   517
        public E next() {
jaroslav@633
   518
            if (expectedModCount != modCount)
jaroslav@633
   519
                throw new ConcurrentModificationException();
jaroslav@633
   520
            if (cursor < size)
jaroslav@633
   521
                return (E) queue[lastRet = cursor++];
jaroslav@633
   522
            if (forgetMeNot != null) {
jaroslav@633
   523
                lastRet = -1;
jaroslav@633
   524
                lastRetElt = forgetMeNot.poll();
jaroslav@633
   525
                if (lastRetElt != null)
jaroslav@633
   526
                    return lastRetElt;
jaroslav@633
   527
            }
jaroslav@633
   528
            throw new NoSuchElementException();
jaroslav@633
   529
        }
jaroslav@633
   530
jaroslav@633
   531
        public void remove() {
jaroslav@633
   532
            if (expectedModCount != modCount)
jaroslav@633
   533
                throw new ConcurrentModificationException();
jaroslav@633
   534
            if (lastRet != -1) {
jaroslav@633
   535
                E moved = PriorityQueue.this.removeAt(lastRet);
jaroslav@633
   536
                lastRet = -1;
jaroslav@633
   537
                if (moved == null)
jaroslav@633
   538
                    cursor--;
jaroslav@633
   539
                else {
jaroslav@633
   540
                    if (forgetMeNot == null)
jaroslav@633
   541
                        forgetMeNot = new ArrayDeque<>();
jaroslav@633
   542
                    forgetMeNot.add(moved);
jaroslav@633
   543
                }
jaroslav@633
   544
            } else if (lastRetElt != null) {
jaroslav@633
   545
                PriorityQueue.this.removeEq(lastRetElt);
jaroslav@633
   546
                lastRetElt = null;
jaroslav@633
   547
            } else {
jaroslav@633
   548
                throw new IllegalStateException();
jaroslav@633
   549
            }
jaroslav@633
   550
            expectedModCount = modCount;
jaroslav@633
   551
        }
jaroslav@633
   552
    }
jaroslav@633
   553
jaroslav@633
   554
    public int size() {
jaroslav@633
   555
        return size;
jaroslav@633
   556
    }
jaroslav@633
   557
jaroslav@633
   558
    /**
jaroslav@633
   559
     * Removes all of the elements from this priority queue.
jaroslav@633
   560
     * The queue will be empty after this call returns.
jaroslav@633
   561
     */
jaroslav@633
   562
    public void clear() {
jaroslav@633
   563
        modCount++;
jaroslav@633
   564
        for (int i = 0; i < size; i++)
jaroslav@633
   565
            queue[i] = null;
jaroslav@633
   566
        size = 0;
jaroslav@633
   567
    }
jaroslav@633
   568
jaroslav@633
   569
    public E poll() {
jaroslav@633
   570
        if (size == 0)
jaroslav@633
   571
            return null;
jaroslav@633
   572
        int s = --size;
jaroslav@633
   573
        modCount++;
jaroslav@633
   574
        E result = (E) queue[0];
jaroslav@633
   575
        E x = (E) queue[s];
jaroslav@633
   576
        queue[s] = null;
jaroslav@633
   577
        if (s != 0)
jaroslav@633
   578
            siftDown(0, x);
jaroslav@633
   579
        return result;
jaroslav@633
   580
    }
jaroslav@633
   581
jaroslav@633
   582
    /**
jaroslav@633
   583
     * Removes the ith element from queue.
jaroslav@633
   584
     *
jaroslav@633
   585
     * Normally this method leaves the elements at up to i-1,
jaroslav@633
   586
     * inclusive, untouched.  Under these circumstances, it returns
jaroslav@633
   587
     * null.  Occasionally, in order to maintain the heap invariant,
jaroslav@633
   588
     * it must swap a later element of the list with one earlier than
jaroslav@633
   589
     * i.  Under these circumstances, this method returns the element
jaroslav@633
   590
     * that was previously at the end of the list and is now at some
jaroslav@633
   591
     * position before i. This fact is used by iterator.remove so as to
jaroslav@633
   592
     * avoid missing traversing elements.
jaroslav@633
   593
     */
jaroslav@633
   594
    private E removeAt(int i) {
jaroslav@633
   595
        assert i >= 0 && i < size;
jaroslav@633
   596
        modCount++;
jaroslav@633
   597
        int s = --size;
jaroslav@633
   598
        if (s == i) // removed last element
jaroslav@633
   599
            queue[i] = null;
jaroslav@633
   600
        else {
jaroslav@633
   601
            E moved = (E) queue[s];
jaroslav@633
   602
            queue[s] = null;
jaroslav@633
   603
            siftDown(i, moved);
jaroslav@633
   604
            if (queue[i] == moved) {
jaroslav@633
   605
                siftUp(i, moved);
jaroslav@633
   606
                if (queue[i] != moved)
jaroslav@633
   607
                    return moved;
jaroslav@633
   608
            }
jaroslav@633
   609
        }
jaroslav@633
   610
        return null;
jaroslav@633
   611
    }
jaroslav@633
   612
jaroslav@633
   613
    /**
jaroslav@633
   614
     * Inserts item x at position k, maintaining heap invariant by
jaroslav@633
   615
     * promoting x up the tree until it is greater than or equal to
jaroslav@633
   616
     * its parent, or is the root.
jaroslav@633
   617
     *
jaroslav@633
   618
     * To simplify and speed up coercions and comparisons. the
jaroslav@633
   619
     * Comparable and Comparator versions are separated into different
jaroslav@633
   620
     * methods that are otherwise identical. (Similarly for siftDown.)
jaroslav@633
   621
     *
jaroslav@633
   622
     * @param k the position to fill
jaroslav@633
   623
     * @param x the item to insert
jaroslav@633
   624
     */
jaroslav@633
   625
    private void siftUp(int k, E x) {
jaroslav@633
   626
        if (comparator != null)
jaroslav@633
   627
            siftUpUsingComparator(k, x);
jaroslav@633
   628
        else
jaroslav@633
   629
            siftUpComparable(k, x);
jaroslav@633
   630
    }
jaroslav@633
   631
jaroslav@633
   632
    private void siftUpComparable(int k, E x) {
jaroslav@633
   633
        Comparable<? super E> key = (Comparable<? super E>) x;
jaroslav@633
   634
        while (k > 0) {
jaroslav@633
   635
            int parent = (k - 1) >>> 1;
jaroslav@633
   636
            Object e = queue[parent];
jaroslav@633
   637
            if (key.compareTo((E) e) >= 0)
jaroslav@633
   638
                break;
jaroslav@633
   639
            queue[k] = e;
jaroslav@633
   640
            k = parent;
jaroslav@633
   641
        }
jaroslav@633
   642
        queue[k] = key;
jaroslav@633
   643
    }
jaroslav@633
   644
jaroslav@633
   645
    private void siftUpUsingComparator(int k, E x) {
jaroslav@633
   646
        while (k > 0) {
jaroslav@633
   647
            int parent = (k - 1) >>> 1;
jaroslav@633
   648
            Object e = queue[parent];
jaroslav@633
   649
            if (comparator.compare(x, (E) e) >= 0)
jaroslav@633
   650
                break;
jaroslav@633
   651
            queue[k] = e;
jaroslav@633
   652
            k = parent;
jaroslav@633
   653
        }
jaroslav@633
   654
        queue[k] = x;
jaroslav@633
   655
    }
jaroslav@633
   656
jaroslav@633
   657
    /**
jaroslav@633
   658
     * Inserts item x at position k, maintaining heap invariant by
jaroslav@633
   659
     * demoting x down the tree repeatedly until it is less than or
jaroslav@633
   660
     * equal to its children or is a leaf.
jaroslav@633
   661
     *
jaroslav@633
   662
     * @param k the position to fill
jaroslav@633
   663
     * @param x the item to insert
jaroslav@633
   664
     */
jaroslav@633
   665
    private void siftDown(int k, E x) {
jaroslav@633
   666
        if (comparator != null)
jaroslav@633
   667
            siftDownUsingComparator(k, x);
jaroslav@633
   668
        else
jaroslav@633
   669
            siftDownComparable(k, x);
jaroslav@633
   670
    }
jaroslav@633
   671
jaroslav@633
   672
    private void siftDownComparable(int k, E x) {
jaroslav@633
   673
        Comparable<? super E> key = (Comparable<? super E>)x;
jaroslav@633
   674
        int half = size >>> 1;        // loop while a non-leaf
jaroslav@633
   675
        while (k < half) {
jaroslav@633
   676
            int child = (k << 1) + 1; // assume left child is least
jaroslav@633
   677
            Object c = queue[child];
jaroslav@633
   678
            int right = child + 1;
jaroslav@633
   679
            if (right < size &&
jaroslav@633
   680
                ((Comparable<? super E>) c).compareTo((E) queue[right]) > 0)
jaroslav@633
   681
                c = queue[child = right];
jaroslav@633
   682
            if (key.compareTo((E) c) <= 0)
jaroslav@633
   683
                break;
jaroslav@633
   684
            queue[k] = c;
jaroslav@633
   685
            k = child;
jaroslav@633
   686
        }
jaroslav@633
   687
        queue[k] = key;
jaroslav@633
   688
    }
jaroslav@633
   689
jaroslav@633
   690
    private void siftDownUsingComparator(int k, E x) {
jaroslav@633
   691
        int half = size >>> 1;
jaroslav@633
   692
        while (k < half) {
jaroslav@633
   693
            int child = (k << 1) + 1;
jaroslav@633
   694
            Object c = queue[child];
jaroslav@633
   695
            int right = child + 1;
jaroslav@633
   696
            if (right < size &&
jaroslav@633
   697
                comparator.compare((E) c, (E) queue[right]) > 0)
jaroslav@633
   698
                c = queue[child = right];
jaroslav@633
   699
            if (comparator.compare(x, (E) c) <= 0)
jaroslav@633
   700
                break;
jaroslav@633
   701
            queue[k] = c;
jaroslav@633
   702
            k = child;
jaroslav@633
   703
        }
jaroslav@633
   704
        queue[k] = x;
jaroslav@633
   705
    }
jaroslav@633
   706
jaroslav@633
   707
    /**
jaroslav@633
   708
     * Establishes the heap invariant (described above) in the entire tree,
jaroslav@633
   709
     * assuming nothing about the order of the elements prior to the call.
jaroslav@633
   710
     */
jaroslav@633
   711
    private void heapify() {
jaroslav@633
   712
        for (int i = (size >>> 1) - 1; i >= 0; i--)
jaroslav@633
   713
            siftDown(i, (E) queue[i]);
jaroslav@633
   714
    }
jaroslav@633
   715
jaroslav@633
   716
    /**
jaroslav@633
   717
     * Returns the comparator used to order the elements in this
jaroslav@633
   718
     * queue, or {@code null} if this queue is sorted according to
jaroslav@633
   719
     * the {@linkplain Comparable natural ordering} of its elements.
jaroslav@633
   720
     *
jaroslav@633
   721
     * @return the comparator used to order this queue, or
jaroslav@633
   722
     *         {@code null} if this queue is sorted according to the
jaroslav@633
   723
     *         natural ordering of its elements
jaroslav@633
   724
     */
jaroslav@633
   725
    public Comparator<? super E> comparator() {
jaroslav@633
   726
        return comparator;
jaroslav@633
   727
    }
jaroslav@633
   728
jaroslav@633
   729
    /**
jaroslav@633
   730
     * Saves the state of the instance to a stream (that
jaroslav@633
   731
     * is, serializes it).
jaroslav@633
   732
     *
jaroslav@633
   733
     * @serialData The length of the array backing the instance is
jaroslav@633
   734
     *             emitted (int), followed by all of its elements
jaroslav@633
   735
     *             (each an {@code Object}) in the proper order.
jaroslav@633
   736
     * @param s the stream
jaroslav@633
   737
     */
jaroslav@633
   738
    private void writeObject(java.io.ObjectOutputStream s)
jaroslav@633
   739
        throws java.io.IOException{
jaroslav@633
   740
        // Write out element count, and any hidden stuff
jaroslav@633
   741
        s.defaultWriteObject();
jaroslav@633
   742
jaroslav@633
   743
        // Write out array length, for compatibility with 1.5 version
jaroslav@633
   744
        s.writeInt(Math.max(2, size + 1));
jaroslav@633
   745
jaroslav@633
   746
        // Write out all elements in the "proper order".
jaroslav@633
   747
        for (int i = 0; i < size; i++)
jaroslav@633
   748
            s.writeObject(queue[i]);
jaroslav@633
   749
    }
jaroslav@633
   750
jaroslav@633
   751
    /**
jaroslav@633
   752
     * Reconstitutes the {@code PriorityQueue} instance from a stream
jaroslav@633
   753
     * (that is, deserializes it).
jaroslav@633
   754
     *
jaroslav@633
   755
     * @param s the stream
jaroslav@633
   756
     */
jaroslav@633
   757
    private void readObject(java.io.ObjectInputStream s)
jaroslav@633
   758
        throws java.io.IOException, ClassNotFoundException {
jaroslav@633
   759
        // Read in size, and any hidden stuff
jaroslav@633
   760
        s.defaultReadObject();
jaroslav@633
   761
jaroslav@633
   762
        // Read in (and discard) array length
jaroslav@633
   763
        s.readInt();
jaroslav@633
   764
jaroslav@633
   765
        queue = new Object[size];
jaroslav@633
   766
jaroslav@633
   767
        // Read in all elements.
jaroslav@633
   768
        for (int i = 0; i < size; i++)
jaroslav@633
   769
            queue[i] = s.readObject();
jaroslav@633
   770
jaroslav@633
   771
        // Elements are guaranteed to be in "proper order", but the
jaroslav@633
   772
        // spec has never explained what that might be.
jaroslav@633
   773
        heapify();
jaroslav@633
   774
    }
jaroslav@633
   775
}