ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/PriorityQueue.java
Revision: 1.121
Committed: Wed Mar 28 02:50:41 2018 UTC (6 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.120: +1 -1 lines
Log Message:
sync Oracle copyright years

File Contents

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