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