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