1 |
< |
package java.util; |
1 |
> |
/* |
2 |
> |
* %W% %E% |
3 |
> |
* |
4 |
> |
* Copyright 2003 Sun Microsystems, Inc. All rights reserved. |
5 |
> |
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. |
6 |
> |
*/ |
7 |
> |
|
8 |
> |
package java.util; |
9 |
|
|
10 |
|
/** |
11 |
< |
* An unbounded priority {@linkplain Queue queue} based on a priority heap. |
12 |
< |
* This queue orders |
13 |
< |
* elements according to an order specified at construction time, which is |
14 |
< |
* specified in the same manner as {@link java.util.TreeSet} and |
15 |
< |
* {@link java.util.TreeMap}: elements are ordered |
16 |
< |
* either according to their <i>natural order</i> (see {@link Comparable}), or |
10 |
< |
* according to a {@link java.util.Comparator}, depending on which |
11 |
< |
* constructor is used. |
11 |
> |
* An unbounded priority {@linkplain Queue queue} based on a priority heap. |
12 |
> |
* This queue orders elements according to an order specified at construction |
13 |
> |
* time, which is specified in the same manner as {@link java.util.TreeSet} |
14 |
> |
* and {@link java.util.TreeMap}: elements are ordered either according to |
15 |
> |
* their <i>natural order</i> (see {@link Comparable}), or according to a |
16 |
> |
* {@link java.util.Comparator}, depending on which constructor is used. |
17 |
|
* <p>The <em>head</em> of this queue is the <em>least</em> element with |
18 |
< |
* respect to the specified ordering. |
19 |
< |
* If multiple elements are tied for least value, the |
15 |
< |
* head is one of those elements. A priority queue does not permit |
18 |
> |
* respect to the specified ordering. If multiple elements are tied for least |
19 |
> |
* value, the head is one of those elements. A priority queue does not permit |
20 |
|
* <tt>null</tt> elements. |
21 |
|
* |
22 |
|
* <p>The {@link #remove()} and {@link #poll()} methods remove and |
32 |
|
* elements are added to a priority queue, its capacity grows |
33 |
|
* automatically. The details of the growth policy are not specified. |
34 |
|
* |
35 |
+ |
* <p>The Iterator provided in method {@link #iterator()} is <em>not</em> |
36 |
+ |
* guaranteed to traverse the elements of the PriorityQueue in any |
37 |
+ |
* particular order. If you need ordered traversal, consider using |
38 |
+ |
* <tt>Arrays.sort(pq.toArray())</tt>. |
39 |
+ |
* |
40 |
+ |
* <p> <strong>Note that this implementation is not synchronized.</strong> |
41 |
+ |
* Multiple threads should not access a <tt>PriorityQueue</tt> |
42 |
+ |
* instance concurrently if any of the threads modifies the list |
43 |
+ |
* structurally. Instead, use the thread-safe {@link |
44 |
+ |
* java.util.concurrent.PriorityBlockingQueue} class. |
45 |
+ |
* |
46 |
+ |
* |
47 |
|
* <p>Implementation note: this implementation provides O(log(n)) time |
48 |
|
* for the insertion methods (<tt>offer</tt>, <tt>poll</tt>, |
49 |
|
* <tt>remove()</tt> and <tt>add</tt>) methods; linear time for the |
55 |
|
* <a href="{@docRoot}/../guide/collections/index.html"> |
56 |
|
* Java Collections Framework</a>. |
57 |
|
* @since 1.5 |
58 |
+ |
* @version %I%, %G% |
59 |
|
* @author Josh Bloch |
60 |
|
*/ |
61 |
|
public class PriorityQueue<E> extends AbstractQueue<E> |
62 |
|
implements Queue<E>, java.io.Serializable { |
63 |
|
|
64 |
+ |
private static final long serialVersionUID = -7720805057305804111L; |
65 |
+ |
|
66 |
|
private static final int DEFAULT_INITIAL_CAPACITY = 11; |
67 |
|
|
68 |
|
/** |
155 |
|
/** |
156 |
|
* Initially fill elements of the queue array under the |
157 |
|
* knowledge that it is sorted or is another PQ, in which |
158 |
< |
* case we can just place the elements without fixups. |
158 |
> |
* case we can just place the elements in the order presented. |
159 |
|
*/ |
160 |
|
private void fillFromSorted(Collection<? extends E> c) { |
161 |
|
for (Iterator<? extends E> i = c.iterator(); i.hasNext(); ) |
162 |
|
queue[++size] = i.next(); |
163 |
|
} |
164 |
|
|
146 |
– |
|
165 |
|
/** |
166 |
< |
* Initially fill elements of the queue array that is |
167 |
< |
* not to our knowledge sorted, so we must add them |
168 |
< |
* one by one. |
166 |
> |
* Initially fill elements of the queue array that is not to our knowledge |
167 |
> |
* sorted, so we must rearrange the elements to guarantee the heap |
168 |
> |
* invariant. |
169 |
|
*/ |
170 |
|
private void fillFromUnsorted(Collection<? extends E> c) { |
171 |
|
for (Iterator<? extends E> i = c.iterator(); i.hasNext(); ) |
172 |
< |
add(i.next()); |
172 |
> |
queue[++size] = i.next(); |
173 |
> |
heapify(); |
174 |
|
} |
175 |
|
|
176 |
|
/** |
195 |
|
*/ |
196 |
|
public PriorityQueue(Collection<? extends E> c) { |
197 |
|
initializeArray(c); |
198 |
< |
if (c instanceof SortedSet<? extends E>) { |
199 |
< |
SortedSet<? extends E> s = (SortedSet<? extends E>) c; |
198 |
> |
if (c instanceof SortedSet) { |
199 |
> |
// @fixme double-cast workaround for compiler |
200 |
> |
SortedSet<? extends E> s = (SortedSet<? extends E>) (SortedSet)c; |
201 |
|
comparator = (Comparator<? super E>)s.comparator(); |
202 |
|
fillFromSorted(s); |
203 |
< |
} else if (c instanceof PriorityQueue<? extends E>) { |
203 |
> |
} else if (c instanceof PriorityQueue) { |
204 |
|
PriorityQueue<? extends E> s = (PriorityQueue<? extends E>) c; |
205 |
|
comparator = (Comparator<? super E>)s.comparator(); |
206 |
|
fillFromSorted(s); |
276 |
|
queue = newQueue; |
277 |
|
} |
278 |
|
|
259 |
– |
// Queue Methods |
260 |
– |
|
279 |
|
|
280 |
+ |
// Queue Methods |
281 |
|
|
282 |
|
/** |
283 |
|
* Add the specified element to this priority queue. |
306 |
|
public E poll() { |
307 |
|
if (size == 0) |
308 |
|
return null; |
309 |
< |
return (E) remove(1); |
309 |
> |
return remove(); |
310 |
|
} |
311 |
|
|
312 |
|
public E peek() { |
349 |
|
} |
350 |
|
|
351 |
|
|
352 |
< |
/** |
352 |
> |
/** |
353 |
|
* Removes a single instance of the specified element from this |
354 |
|
* queue, if it is present. More formally, |
355 |
|
* removes an element <tt>e</tt> such that <tt>(o==null ? e==null : |
370 |
|
if (comparator == null) { |
371 |
|
for (int i = 1; i <= size; i++) { |
372 |
|
if (((Comparable<E>)queue[i]).compareTo((E)o) == 0) { |
373 |
< |
remove(i); |
373 |
> |
removeAt(i); |
374 |
|
return true; |
375 |
|
} |
376 |
|
} |
377 |
|
} else { |
378 |
|
for (int i = 1; i <= size; i++) { |
379 |
|
if (comparator.compare((E)queue[i], (E)o) == 0) { |
380 |
< |
remove(i); |
380 |
> |
removeAt(i); |
381 |
|
return true; |
382 |
|
} |
383 |
|
} |
396 |
|
} |
397 |
|
|
398 |
|
private class Itr implements Iterator<E> { |
399 |
+ |
|
400 |
|
/** |
401 |
|
* Index (into queue array) of element to be returned by |
402 |
|
* subsequent call to next. |
404 |
|
private int cursor = 1; |
405 |
|
|
406 |
|
/** |
407 |
< |
* Index of element returned by most recent call to next or |
408 |
< |
* previous. Reset to 0 if this element is deleted by a call |
409 |
< |
* to remove. |
407 |
> |
* Index of element returned by most recent call to next, |
408 |
> |
* unless that element came from the forgetMeNot list. |
409 |
> |
* Reset to 0 if element is deleted by a call to remove. |
410 |
|
*/ |
411 |
|
private int lastRet = 0; |
412 |
|
|
417 |
|
*/ |
418 |
|
private int expectedModCount = modCount; |
419 |
|
|
420 |
+ |
/** |
421 |
+ |
* A list of elements that were moved from the unvisited portion of |
422 |
+ |
* the heap into the visited portion as a result of "unlucky" element |
423 |
+ |
* removals during the iteration. (Unlucky element removals are those |
424 |
+ |
* that require a fixup instead of a fixdown.) We must visit all of |
425 |
+ |
* the elements in this list to complete the iteration. We do this |
426 |
+ |
* after we've completed the "normal" iteration. |
427 |
+ |
* |
428 |
+ |
* We expect that most iterations, even those involving removals, |
429 |
+ |
* will not use need to store elements in this field. |
430 |
+ |
*/ |
431 |
+ |
private ArrayList<E> forgetMeNot = null; |
432 |
+ |
|
433 |
+ |
/** |
434 |
+ |
* Element returned by the most recent call to next iff that |
435 |
+ |
* element was drawn from the forgetMeNot list. |
436 |
+ |
*/ |
437 |
+ |
private Object lastRetElt = null; |
438 |
+ |
|
439 |
|
public boolean hasNext() { |
440 |
< |
return cursor <= size; |
440 |
> |
return cursor <= size || forgetMeNot != null; |
441 |
|
} |
442 |
|
|
443 |
|
public E next() { |
444 |
|
checkForComodification(); |
445 |
< |
if (cursor > size) |
445 |
> |
E result; |
446 |
> |
if (cursor <= size) { |
447 |
> |
result = (E) queue[cursor]; |
448 |
> |
lastRet = cursor++; |
449 |
> |
} |
450 |
> |
else if (forgetMeNot == null) |
451 |
|
throw new NoSuchElementException(); |
452 |
< |
E result = (E) queue[cursor]; |
453 |
< |
lastRet = cursor++; |
452 |
> |
else { |
453 |
> |
int remaining = forgetMeNot.size(); |
454 |
> |
result = forgetMeNot.remove(remaining - 1); |
455 |
> |
if (remaining == 1) |
456 |
> |
forgetMeNot = null; |
457 |
> |
lastRet = 0; |
458 |
> |
lastRetElt = result; |
459 |
> |
} |
460 |
|
return result; |
461 |
|
} |
462 |
|
|
463 |
|
public void remove() { |
414 |
– |
if (lastRet == 0) |
415 |
– |
throw new IllegalStateException(); |
464 |
|
checkForComodification(); |
465 |
|
|
466 |
< |
PriorityQueue.this.remove(lastRet); |
467 |
< |
if (lastRet < cursor) |
468 |
< |
cursor--; |
469 |
< |
lastRet = 0; |
466 |
> |
if (lastRet != 0) { |
467 |
> |
E moved = PriorityQueue.this.removeAt(lastRet); |
468 |
> |
lastRet = 0; |
469 |
> |
if (moved == null) { |
470 |
> |
cursor--; |
471 |
> |
} else { |
472 |
> |
if (forgetMeNot == null) |
473 |
> |
forgetMeNot = new ArrayList<E>(); |
474 |
> |
forgetMeNot.add(moved); |
475 |
> |
} |
476 |
> |
} else if (lastRetElt != null) { |
477 |
> |
PriorityQueue.this.remove(lastRetElt); |
478 |
> |
lastRetElt = null; |
479 |
> |
} else { |
480 |
> |
throw new IllegalStateException(); |
481 |
> |
} |
482 |
> |
|
483 |
|
expectedModCount = modCount; |
484 |
|
} |
485 |
|
|
507 |
|
} |
508 |
|
|
509 |
|
/** |
510 |
< |
* Removes and returns the ith element from queue. Recall |
511 |
< |
* that queue is one-based, so 1 <= i <= size. |
510 |
> |
* Removes and returns the first element from queue. |
511 |
> |
*/ |
512 |
> |
public E remove() { |
513 |
> |
if (size == 0) |
514 |
> |
throw new NoSuchElementException(); |
515 |
> |
modCount++; |
516 |
> |
|
517 |
> |
E result = (E) queue[1]; |
518 |
> |
queue[1] = queue[size]; |
519 |
> |
queue[size--] = null; // Drop extra ref to prevent memory leak |
520 |
> |
if (size > 1) |
521 |
> |
fixDown(1); |
522 |
> |
|
523 |
> |
return result; |
524 |
> |
} |
525 |
> |
|
526 |
> |
/** |
527 |
> |
* Removes and returns the ith element from queue. (Recall that queue |
528 |
> |
* is one-based, so 1 <= i <= size.) |
529 |
|
* |
530 |
< |
* XXX: Could further special-case i==size, but is it worth it? |
531 |
< |
* XXX: Could special-case i==0, but is it worth it? |
530 |
> |
* Normally this method leaves the elements at positions from 1 up to i-1, |
531 |
> |
* inclusive, untouched. Under these circumstances, it returns null. |
532 |
> |
* Occasionally, in order to maintain the heap invariant, it must move |
533 |
> |
* the last element of the list to some index in the range [2, i-1], |
534 |
> |
* and move the element previously at position (i/2) to position i. |
535 |
> |
* Under these circumstances, this method returns the element that was |
536 |
> |
* previously at the end of the list and is now at some position between |
537 |
> |
* 2 and i-1 inclusive. |
538 |
|
*/ |
539 |
< |
private E remove(int i) { |
540 |
< |
assert i <= size; |
539 |
> |
private E removeAt(int i) { |
540 |
> |
assert i > 0 && i <= size; |
541 |
|
modCount++; |
542 |
|
|
543 |
< |
E result = (E) queue[i]; |
544 |
< |
queue[i] = queue[size]; |
543 |
> |
E moved = (E) queue[size]; |
544 |
> |
queue[i] = moved; |
545 |
|
queue[size--] = null; // Drop extra ref to prevent memory leak |
546 |
< |
if (i <= size) |
546 |
> |
if (i <= size) { |
547 |
|
fixDown(i); |
548 |
< |
return result; |
548 |
> |
if (queue[i] == moved) { |
549 |
> |
fixUp(i); |
550 |
> |
if (queue[i] != moved) |
551 |
> |
return moved; |
552 |
> |
} |
553 |
> |
} |
554 |
> |
return null; |
555 |
|
} |
556 |
|
|
557 |
|
/** |
574 |
|
} |
575 |
|
} else { |
576 |
|
while (k > 1) { |
577 |
< |
int j = k >> 1; |
577 |
> |
int j = k >>> 1; |
578 |
|
if (comparator.compare((E)queue[j], (E)queue[k]) <= 0) |
579 |
|
break; |
580 |
|
Object tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; |
595 |
|
private void fixDown(int k) { |
596 |
|
int j; |
597 |
|
if (comparator == null) { |
598 |
< |
while ((j = k << 1) <= size) { |
599 |
< |
if (j<size && ((Comparable<E>)queue[j]).compareTo((E)queue[j+1]) > 0) |
598 |
> |
while ((j = k << 1) <= size && (j > 0)) { |
599 |
> |
if (j<size && |
600 |
> |
((Comparable<E>)queue[j]).compareTo((E)queue[j+1]) > 0) |
601 |
|
j++; // j indexes smallest kid |
602 |
+ |
|
603 |
|
if (((Comparable<E>)queue[k]).compareTo((E)queue[j]) <= 0) |
604 |
|
break; |
605 |
|
Object tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; |
606 |
|
k = j; |
607 |
|
} |
608 |
|
} else { |
609 |
< |
while ((j = k << 1) <= size) { |
610 |
< |
if (j < size && comparator.compare((E)queue[j], (E)queue[j+1]) > 0) |
609 |
> |
while ((j = k << 1) <= size && (j > 0)) { |
610 |
> |
if (j<size && |
611 |
> |
comparator.compare((E)queue[j], (E)queue[j+1]) > 0) |
612 |
|
j++; // j indexes smallest kid |
613 |
|
if (comparator.compare((E)queue[k], (E)queue[j]) <= 0) |
614 |
|
break; |
618 |
|
} |
619 |
|
} |
620 |
|
|
621 |
+ |
/** |
622 |
+ |
* Establishes the heap invariant (described above) in the entire tree, |
623 |
+ |
* assuming nothing about the order of the elements prior to the call. |
624 |
+ |
*/ |
625 |
+ |
private void heapify() { |
626 |
+ |
for (int i = size/2; i >= 1; i--) |
627 |
+ |
fixDown(i); |
628 |
+ |
} |
629 |
|
|
630 |
|
/** |
631 |
|
* Returns the comparator used to order this collection, or <tt>null</tt> |
657 |
|
s.writeInt(queue.length); |
658 |
|
|
659 |
|
// Write out all elements in the proper order. |
660 |
< |
for (int i=0; i<size; i++) |
660 |
> |
for (int i=1; i<=size; i++) |
661 |
|
s.writeObject(queue[i]); |
662 |
|
} |
663 |
|
|
676 |
|
queue = new Object[arrayLength]; |
677 |
|
|
678 |
|
// Read in all elements in the proper order. |
679 |
< |
for (int i=0; i<size; i++) |
680 |
< |
queue[i] = s.readObject(); |
679 |
> |
for (int i=1; i<=size; i++) |
680 |
> |
queue[i] = (E) s.readObject(); |
681 |
|
} |
682 |
|
|
683 |
|
} |
583 |
– |
|