1 |
< |
package java.util; |
1 |
> |
/* |
2 |
> |
* %W% %E% |
3 |
> |
* |
4 |
> |
* Copyright 2004 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 |
17 |
< |
* according to a {@link java.util.Comparator}, depending on which |
18 |
< |
* constructor is used. |
19 |
< |
* <p>The <em>head</em> of this queue is the <em>least</em> element with |
20 |
< |
* respect to the specified ordering. |
21 |
< |
* If multiple elements are tied for least value, the |
22 |
< |
* head is one of those elements. A priority queue does not permit |
23 |
< |
* <tt>null</tt> elements. |
11 |
> |
* An unbounded priority {@linkplain Queue queue} based on a priority |
12 |
> |
* heap. This queue orders elements according to an order specified |
13 |
> |
* at construction time, which is specified either according to their |
14 |
> |
* <i>natural order</i> (see {@link Comparable}), or according to a |
15 |
> |
* {@link java.util.Comparator}, depending on which constructor is |
16 |
> |
* used. A priority queue does not permit <tt>null</tt> elements. |
17 |
> |
* A priority queue relying on natural ordering also does not |
18 |
> |
* permit insertion of non-comparable objects (doing so may result |
19 |
> |
* in <tt>ClassCastException</tt>). |
20 |
> |
* |
21 |
> |
* <p>The <em>head</em> of this queue is the <em>least</em> element |
22 |
> |
* with respect to the specified ordering. If multiple elements are |
23 |
> |
* tied for least value, the head is one of those elements -- ties are |
24 |
> |
* broken arbitrarily. The queue retrieval operations <tt>poll</tt>, |
25 |
> |
* <tt>remove</tt>, <tt>peek</tt>, and <tt>element</tt> access the |
26 |
> |
* element at the head of the queue. |
27 |
|
* |
28 |
< |
* <p>The {@link #remove()} and {@link #poll()} methods remove and |
29 |
< |
* return the head of the queue. |
28 |
> |
* <p>A priority queue is unbounded, but has an internal |
29 |
> |
* <i>capacity</i> governing the size of an array used to store the |
30 |
> |
* elements on the queue. It is always at least as large as the queue |
31 |
> |
* size. As elements are added to a priority queue, its capacity |
32 |
> |
* grows automatically. The details of the growth policy are not |
33 |
> |
* specified. |
34 |
|
* |
35 |
< |
* <p>The {@link #element()} and {@link #peek()} methods return, but do |
36 |
< |
* not delete, the head of the queue. |
35 |
> |
* <p>This class and its iterator implement all of the |
36 |
> |
* <em>optional</em> methods of the {@link Collection} and {@link |
37 |
> |
* Iterator} interfaces. |
38 |
> |
* The |
39 |
> |
* Iterator provided in method {@link #iterator()} is <em>not</em> |
40 |
> |
* guaranteed to traverse the elements of the PriorityQueue in any |
41 |
> |
* particular order. If you need ordered traversal, consider using |
42 |
> |
* <tt>Arrays.sort(pq.toArray())</tt>. |
43 |
|
* |
44 |
< |
* <p>A priority queue has a <i>capacity</i>. The capacity is the |
45 |
< |
* size of the array used internally to store the elements on the |
46 |
< |
* queue. |
47 |
< |
* It is always at least as large as the queue size. As |
48 |
< |
* elements are added to a priority queue, its capacity grows |
29 |
< |
* automatically. The details of the growth policy are not specified. |
44 |
> |
* <p> <strong>Note that this implementation is not synchronized.</strong> |
45 |
> |
* Multiple threads should not access a <tt>PriorityQueue</tt> |
46 |
> |
* instance concurrently if any of the threads modifies the list |
47 |
> |
* structurally. Instead, use the thread-safe {@link |
48 |
> |
* java.util.concurrent.PriorityBlockingQueue} class. |
49 |
|
* |
50 |
+ |
* |
51 |
|
* <p>Implementation note: this implementation provides O(log(n)) time |
52 |
|
* for the insertion methods (<tt>offer</tt>, <tt>poll</tt>, |
53 |
|
* <tt>remove()</tt> and <tt>add</tt>) methods; linear time for the |
59 |
|
* <a href="{@docRoot}/../guide/collections/index.html"> |
60 |
|
* Java Collections Framework</a>. |
61 |
|
* @since 1.5 |
62 |
+ |
* @version %I%, %G% |
63 |
|
* @author Josh Bloch |
64 |
+ |
* @param <E> the type of elements held in this collection |
65 |
|
*/ |
66 |
|
public class PriorityQueue<E> extends AbstractQueue<E> |
67 |
< |
implements Queue<E>, java.io.Serializable { |
67 |
> |
implements java.io.Serializable { |
68 |
> |
|
69 |
> |
private static final long serialVersionUID = -7720805057305804111L; |
70 |
|
|
71 |
|
private static final int DEFAULT_INITIAL_CAPACITY = 11; |
72 |
|
|
160 |
|
/** |
161 |
|
* Initially fill elements of the queue array under the |
162 |
|
* knowledge that it is sorted or is another PQ, in which |
163 |
< |
* case we can just place the elements without fixups. |
163 |
> |
* case we can just place the elements in the order presented. |
164 |
|
*/ |
165 |
|
private void fillFromSorted(Collection<? extends E> c) { |
166 |
|
for (Iterator<? extends E> i = c.iterator(); i.hasNext(); ) |
167 |
|
queue[++size] = i.next(); |
168 |
|
} |
169 |
|
|
146 |
– |
|
170 |
|
/** |
171 |
< |
* Initially fill elements of the queue array that is |
172 |
< |
* not to our knowledge sorted, so we must add them |
173 |
< |
* one by one. |
171 |
> |
* Initially fill elements of the queue array that is not to our knowledge |
172 |
> |
* sorted, so we must rearrange the elements to guarantee the heap |
173 |
> |
* invariant. |
174 |
|
*/ |
175 |
|
private void fillFromUnsorted(Collection<? extends E> c) { |
176 |
|
for (Iterator<? extends E> i = c.iterator(); i.hasNext(); ) |
177 |
< |
add(i.next()); |
177 |
> |
queue[++size] = i.next(); |
178 |
> |
heapify(); |
179 |
|
} |
180 |
|
|
181 |
|
/** |
200 |
|
*/ |
201 |
|
public PriorityQueue(Collection<? extends E> c) { |
202 |
|
initializeArray(c); |
203 |
< |
if (c instanceof SortedSet<? extends E>) { |
204 |
< |
SortedSet<? extends E> s = (SortedSet<? extends E>) c; |
203 |
> |
if (c instanceof SortedSet) { |
204 |
> |
SortedSet<? extends E> s = (SortedSet<? extends E>)c; |
205 |
|
comparator = (Comparator<? super E>)s.comparator(); |
206 |
|
fillFromSorted(s); |
207 |
< |
} |
184 |
< |
else if (c instanceof PriorityQueue<? extends E>) { |
207 |
> |
} else if (c instanceof PriorityQueue) { |
208 |
|
PriorityQueue<? extends E> s = (PriorityQueue<? extends E>) c; |
209 |
|
comparator = (Comparator<? super E>)s.comparator(); |
210 |
|
fillFromSorted(s); |
211 |
< |
} |
189 |
< |
else { |
211 |
> |
} else { |
212 |
|
comparator = null; |
213 |
|
fillFromUnsorted(c); |
214 |
|
} |
280 |
|
queue = newQueue; |
281 |
|
} |
282 |
|
|
261 |
– |
// Queue Methods |
262 |
– |
|
263 |
– |
|
283 |
|
|
284 |
|
/** |
285 |
< |
* Add the specified element to this priority queue. |
285 |
> |
* Inserts the specified element into this priority queue. |
286 |
|
* |
287 |
|
* @return <tt>true</tt> |
288 |
|
* @throws ClassCastException if the specified element cannot be compared |
305 |
|
return true; |
306 |
|
} |
307 |
|
|
308 |
< |
public E poll() { |
308 |
> |
public E peek() { |
309 |
|
if (size == 0) |
310 |
|
return null; |
292 |
– |
return (E) remove(1); |
293 |
– |
} |
294 |
– |
|
295 |
– |
public E peek() { |
311 |
|
return (E) queue[1]; |
312 |
|
} |
313 |
|
|
318 |
|
* @return <tt>true</tt> (as per the general contract of |
319 |
|
* <tt>Collection.add</tt>). |
320 |
|
* |
321 |
< |
* @throws NullPointerException {@inheritDoc} |
321 |
> |
* @throws NullPointerException if the specified element is <tt>null</tt>. |
322 |
|
* @throws ClassCastException if the specified element cannot be compared |
323 |
|
* with elements currently in the priority queue according |
324 |
|
* to the priority queue's ordering. |
325 |
|
*/ |
326 |
|
public boolean add(E o) { |
327 |
< |
return super.add(o); |
327 |
> |
return offer(o); |
328 |
|
} |
329 |
|
|
315 |
– |
|
330 |
|
/** |
317 |
– |
* Adds all of the elements in the specified collection to this queue. |
318 |
– |
* The behavior of this operation is undefined if |
319 |
– |
* the specified collection is modified while the operation is in |
320 |
– |
* progress. (This implies that the behavior of this call is undefined if |
321 |
– |
* the specified collection is this queue, and this queue is nonempty.) |
322 |
– |
* <p> |
323 |
– |
* This implementation iterates over the specified collection, and adds |
324 |
– |
* each object returned by the iterator to this collection, in turn. |
325 |
– |
* @throws NullPointerException {@inheritDoc} |
326 |
– |
* @throws ClassCastException if any element cannot be compared |
327 |
– |
* with elements currently in the priority queue according |
328 |
– |
* to the priority queue's ordering. |
329 |
– |
*/ |
330 |
– |
public boolean addAll(Collection<? extends E> c) { |
331 |
– |
return super.addAll(c); |
332 |
– |
} |
333 |
– |
|
334 |
– |
|
335 |
– |
/** |
331 |
|
* Removes a single instance of the specified element from this |
332 |
< |
* queue, if it is present. More formally, |
338 |
< |
* removes an element <tt>e</tt> such that <tt>(o==null ? e==null : |
339 |
< |
* o.equals(e))</tt>, if the queue contains one or more such |
340 |
< |
* elements. Returns <tt>true</tt> if the queue contained the |
341 |
< |
* specified element (or equivalently, if the queue changed as a |
342 |
< |
* result of the call). |
343 |
< |
* |
344 |
< |
* <p>This implementation iterates over the queue looking for the |
345 |
< |
* specified element. If it finds the element, it removes the element |
346 |
< |
* from the queue using the iterator's remove method.<p> |
347 |
< |
* |
332 |
> |
* queue, if it is present. |
333 |
|
*/ |
334 |
|
public boolean remove(Object o) { |
335 |
|
if (o == null) |
338 |
|
if (comparator == null) { |
339 |
|
for (int i = 1; i <= size; i++) { |
340 |
|
if (((Comparable<E>)queue[i]).compareTo((E)o) == 0) { |
341 |
< |
remove(i); |
341 |
> |
removeAt(i); |
342 |
|
return true; |
343 |
|
} |
344 |
|
} |
345 |
|
} else { |
346 |
|
for (int i = 1; i <= size; i++) { |
347 |
|
if (comparator.compare((E)queue[i], (E)o) == 0) { |
348 |
< |
remove(i); |
348 |
> |
removeAt(i); |
349 |
|
return true; |
350 |
|
} |
351 |
|
} |
364 |
|
} |
365 |
|
|
366 |
|
private class Itr implements Iterator<E> { |
367 |
+ |
|
368 |
|
/** |
369 |
|
* Index (into queue array) of element to be returned by |
370 |
|
* subsequent call to next. |
372 |
|
private int cursor = 1; |
373 |
|
|
374 |
|
/** |
375 |
< |
* Index of element returned by most recent call to next or |
376 |
< |
* previous. Reset to 0 if this element is deleted by a call |
377 |
< |
* to remove. |
375 |
> |
* Index of element returned by most recent call to next, |
376 |
> |
* unless that element came from the forgetMeNot list. |
377 |
> |
* Reset to 0 if element is deleted by a call to remove. |
378 |
|
*/ |
379 |
|
private int lastRet = 0; |
380 |
|
|
385 |
|
*/ |
386 |
|
private int expectedModCount = modCount; |
387 |
|
|
388 |
+ |
/** |
389 |
+ |
* A list of elements that were moved from the unvisited portion of |
390 |
+ |
* the heap into the visited portion as a result of "unlucky" element |
391 |
+ |
* removals during the iteration. (Unlucky element removals are those |
392 |
+ |
* that require a fixup instead of a fixdown.) We must visit all of |
393 |
+ |
* the elements in this list to complete the iteration. We do this |
394 |
+ |
* after we've completed the "normal" iteration. |
395 |
+ |
* |
396 |
+ |
* We expect that most iterations, even those involving removals, |
397 |
+ |
* will not use need to store elements in this field. |
398 |
+ |
*/ |
399 |
+ |
private ArrayList<E> forgetMeNot = null; |
400 |
+ |
|
401 |
+ |
/** |
402 |
+ |
* Element returned by the most recent call to next iff that |
403 |
+ |
* element was drawn from the forgetMeNot list. |
404 |
+ |
*/ |
405 |
+ |
private Object lastRetElt = null; |
406 |
+ |
|
407 |
|
public boolean hasNext() { |
408 |
< |
return cursor <= size; |
408 |
> |
return cursor <= size || forgetMeNot != null; |
409 |
|
} |
410 |
|
|
411 |
|
public E next() { |
412 |
|
checkForComodification(); |
413 |
< |
if (cursor > size) |
413 |
> |
E result; |
414 |
> |
if (cursor <= size) { |
415 |
> |
result = (E) queue[cursor]; |
416 |
> |
lastRet = cursor++; |
417 |
> |
} |
418 |
> |
else if (forgetMeNot == null) |
419 |
|
throw new NoSuchElementException(); |
420 |
< |
E result = (E) queue[cursor]; |
421 |
< |
lastRet = cursor++; |
420 |
> |
else { |
421 |
> |
int remaining = forgetMeNot.size(); |
422 |
> |
result = forgetMeNot.remove(remaining - 1); |
423 |
> |
if (remaining == 1) |
424 |
> |
forgetMeNot = null; |
425 |
> |
lastRet = 0; |
426 |
> |
lastRetElt = result; |
427 |
> |
} |
428 |
|
return result; |
429 |
|
} |
430 |
|
|
431 |
|
public void remove() { |
416 |
– |
if (lastRet == 0) |
417 |
– |
throw new IllegalStateException(); |
432 |
|
checkForComodification(); |
433 |
|
|
434 |
< |
PriorityQueue.this.remove(lastRet); |
435 |
< |
if (lastRet < cursor) |
436 |
< |
cursor--; |
437 |
< |
lastRet = 0; |
434 |
> |
if (lastRet != 0) { |
435 |
> |
E moved = PriorityQueue.this.removeAt(lastRet); |
436 |
> |
lastRet = 0; |
437 |
> |
if (moved == null) { |
438 |
> |
cursor--; |
439 |
> |
} else { |
440 |
> |
if (forgetMeNot == null) |
441 |
> |
forgetMeNot = new ArrayList<E>(); |
442 |
> |
forgetMeNot.add(moved); |
443 |
> |
} |
444 |
> |
} else if (lastRetElt != null) { |
445 |
> |
PriorityQueue.this.remove(lastRetElt); |
446 |
> |
lastRetElt = null; |
447 |
> |
} else { |
448 |
> |
throw new IllegalStateException(); |
449 |
> |
} |
450 |
> |
|
451 |
|
expectedModCount = modCount; |
452 |
|
} |
453 |
|
|
462 |
|
} |
463 |
|
|
464 |
|
/** |
465 |
< |
* Remove all elements from the priority queue. |
465 |
> |
* Removes all elements from the priority queue. |
466 |
> |
* The queue will be empty after this call returns. |
467 |
|
*/ |
468 |
|
public void clear() { |
469 |
|
modCount++; |
475 |
|
size = 0; |
476 |
|
} |
477 |
|
|
478 |
+ |
public E poll() { |
479 |
+ |
if (size == 0) |
480 |
+ |
return null; |
481 |
+ |
modCount++; |
482 |
+ |
|
483 |
+ |
E result = (E) queue[1]; |
484 |
+ |
queue[1] = queue[size]; |
485 |
+ |
queue[size--] = null; // Drop extra ref to prevent memory leak |
486 |
+ |
if (size > 1) |
487 |
+ |
fixDown(1); |
488 |
+ |
|
489 |
+ |
return result; |
490 |
+ |
} |
491 |
+ |
|
492 |
|
/** |
493 |
< |
* Removes and returns the ith element from queue. Recall |
494 |
< |
* that queue is one-based, so 1 <= i <= size. |
493 |
> |
* Removes and returns the ith element from queue. (Recall that queue |
494 |
> |
* is one-based, so 1 <= i <= size.) |
495 |
|
* |
496 |
< |
* XXX: Could further special-case i==size, but is it worth it? |
497 |
< |
* XXX: Could special-case i==0, but is it worth it? |
496 |
> |
* Normally this method leaves the elements at positions from 1 up to i-1, |
497 |
> |
* inclusive, untouched. Under these circumstances, it returns null. |
498 |
> |
* Occasionally, in order to maintain the heap invariant, it must move |
499 |
> |
* the last element of the list to some index in the range [2, i-1], |
500 |
> |
* and move the element previously at position (i/2) to position i. |
501 |
> |
* Under these circumstances, this method returns the element that was |
502 |
> |
* previously at the end of the list and is now at some position between |
503 |
> |
* 2 and i-1 inclusive. |
504 |
|
*/ |
505 |
< |
private E remove(int i) { |
506 |
< |
assert i <= size; |
505 |
> |
private E removeAt(int i) { |
506 |
> |
assert i > 0 && i <= size; |
507 |
|
modCount++; |
508 |
|
|
509 |
< |
E result = (E) queue[i]; |
510 |
< |
queue[i] = queue[size]; |
509 |
> |
E moved = (E) queue[size]; |
510 |
> |
queue[i] = moved; |
511 |
|
queue[size--] = null; // Drop extra ref to prevent memory leak |
512 |
< |
if (i <= size) |
512 |
> |
if (i <= size) { |
513 |
|
fixDown(i); |
514 |
< |
return result; |
514 |
> |
if (queue[i] == moved) { |
515 |
> |
fixUp(i); |
516 |
> |
if (queue[i] != moved) |
517 |
> |
return moved; |
518 |
> |
} |
519 |
> |
} |
520 |
> |
return null; |
521 |
|
} |
522 |
|
|
523 |
|
/** |
540 |
|
} |
541 |
|
} else { |
542 |
|
while (k > 1) { |
543 |
< |
int j = k >> 1; |
543 |
> |
int j = k >>> 1; |
544 |
|
if (comparator.compare((E)queue[j], (E)queue[k]) <= 0) |
545 |
|
break; |
546 |
|
Object tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; |
561 |
|
private void fixDown(int k) { |
562 |
|
int j; |
563 |
|
if (comparator == null) { |
564 |
< |
while ((j = k << 1) <= size) { |
565 |
< |
if (j<size && ((Comparable<E>)queue[j]).compareTo((E)queue[j+1]) > 0) |
564 |
> |
while ((j = k << 1) <= size && (j > 0)) { |
565 |
> |
if (j<size && |
566 |
> |
((Comparable<E>)queue[j]).compareTo((E)queue[j+1]) > 0) |
567 |
|
j++; // j indexes smallest kid |
568 |
+ |
|
569 |
|
if (((Comparable<E>)queue[k]).compareTo((E)queue[j]) <= 0) |
570 |
|
break; |
571 |
|
Object tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; |
572 |
|
k = j; |
573 |
|
} |
574 |
|
} else { |
575 |
< |
while ((j = k << 1) <= size) { |
576 |
< |
if (j < size && comparator.compare((E)queue[j], (E)queue[j+1]) > 0) |
575 |
> |
while ((j = k << 1) <= size && (j > 0)) { |
576 |
> |
if (j<size && |
577 |
> |
comparator.compare((E)queue[j], (E)queue[j+1]) > 0) |
578 |
|
j++; // j indexes smallest kid |
579 |
|
if (comparator.compare((E)queue[k], (E)queue[j]) <= 0) |
580 |
|
break; |
584 |
|
} |
585 |
|
} |
586 |
|
|
587 |
+ |
/** |
588 |
+ |
* Establishes the heap invariant (described above) in the entire tree, |
589 |
+ |
* assuming nothing about the order of the elements prior to the call. |
590 |
+ |
*/ |
591 |
+ |
private void heapify() { |
592 |
+ |
for (int i = size/2; i >= 1; i--) |
593 |
+ |
fixDown(i); |
594 |
+ |
} |
595 |
|
|
596 |
|
/** |
597 |
|
* Returns the comparator used to order this collection, or <tt>null</tt> |
623 |
|
s.writeInt(queue.length); |
624 |
|
|
625 |
|
// Write out all elements in the proper order. |
626 |
< |
for (int i=0; i<size; i++) |
626 |
> |
for (int i=1; i<=size; i++) |
627 |
|
s.writeObject(queue[i]); |
628 |
|
} |
629 |
|
|
642 |
|
queue = new Object[arrayLength]; |
643 |
|
|
644 |
|
// Read in all elements in the proper order. |
645 |
< |
for (int i=0; i<size; i++) |
646 |
< |
queue[i] = s.readObject(); |
645 |
> |
for (int i=1; i<=size; i++) |
646 |
> |
queue[i] = (E) s.readObject(); |
647 |
|
} |
648 |
|
|
649 |
|
} |
585 |
– |
|