ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/PriorityQueue.java
Revision: 1.49
Committed: Thu May 27 11:05:44 2004 UTC (19 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.48: +6 -1 lines
Log Message:
Override javadoc specs when overriding AbstractQueue implementations

File Contents

# Content
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
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>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>This class implements all of the <em>optional</em> methods of
36 * the {@link Collection} and {@link Iterator} interfaces. The
37 * Iterator provided in method {@link #iterator()} is <em>not</em>
38 * guaranteed to traverse the elements of the PriorityQueue in any
39 * particular order. If you need ordered traversal, consider using
40 * <tt>Arrays.sort(pq.toArray())</tt>.
41 *
42 * <p> <strong>Note that this implementation is not synchronized.</strong>
43 * Multiple threads should not access a <tt>PriorityQueue</tt>
44 * instance concurrently if any of the threads modifies the list
45 * structurally. Instead, use the thread-safe {@link
46 * java.util.concurrent.PriorityBlockingQueue} class.
47 *
48 *
49 * <p>Implementation note: this implementation provides O(log(n)) time
50 * for the insertion methods (<tt>offer</tt>, <tt>poll</tt>,
51 * <tt>remove()</tt> and <tt>add</tt>) methods; linear time for the
52 * <tt>remove(Object)</tt> and <tt>contains(Object)</tt> methods; and
53 * constant time for the retrieval methods (<tt>peek</tt>,
54 * <tt>element</tt>, and <tt>size</tt>).
55 *
56 * <p>This class is a member of the
57 * <a href="{@docRoot}/../guide/collections/index.html">
58 * Java Collections Framework</a>.
59 * @since 1.5
60 * @version %I%, %G%
61 * @author Josh Bloch
62 * @param <E> the type of elements held in this collection
63 */
64 public class PriorityQueue<E> extends AbstractQueue<E>
65 implements java.io.Serializable {
66
67 private static final long serialVersionUID = -7720805057305804111L;
68
69 private static final int DEFAULT_INITIAL_CAPACITY = 11;
70
71 /**
72 * Priority queue represented as a balanced binary heap: the two children
73 * of queue[n] are queue[2*n] and queue[2*n + 1]. The priority queue is
74 * ordered by comparator, or by the elements' natural ordering, if
75 * comparator is null: For each node n in the heap and each descendant d
76 * of n, n <= d.
77 *
78 * The element with the lowest value is in queue[1], assuming the queue is
79 * nonempty. (A one-based array is used in preference to the traditional
80 * zero-based array to simplify parent and child calculations.)
81 *
82 * queue.length must be >= 2, even if size == 0.
83 */
84 private transient Object[] queue;
85
86 /**
87 * The number of elements in the priority queue.
88 */
89 private int size = 0;
90
91 /**
92 * The comparator, or null if priority queue uses elements'
93 * natural ordering.
94 */
95 private final Comparator<? super E> comparator;
96
97 /**
98 * The number of times this priority queue has been
99 * <i>structurally modified</i>. See AbstractList for gory details.
100 */
101 private transient int modCount = 0;
102
103 /**
104 * Creates a <tt>PriorityQueue</tt> with the default initial capacity
105 * (11) that orders its elements according to their natural
106 * ordering (using <tt>Comparable</tt>).
107 */
108 public PriorityQueue() {
109 this(DEFAULT_INITIAL_CAPACITY, null);
110 }
111
112 /**
113 * Creates a <tt>PriorityQueue</tt> with the specified initial capacity
114 * that orders its elements according to their natural ordering
115 * (using <tt>Comparable</tt>).
116 *
117 * @param initialCapacity the initial capacity for this priority queue.
118 * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
119 * than 1
120 */
121 public PriorityQueue(int initialCapacity) {
122 this(initialCapacity, null);
123 }
124
125 /**
126 * Creates a <tt>PriorityQueue</tt> with the specified initial capacity
127 * that orders its elements according to the specified comparator.
128 *
129 * @param initialCapacity the initial capacity for this priority queue.
130 * @param comparator the comparator used to order this priority queue.
131 * If <tt>null</tt> then the order depends on the elements' natural
132 * ordering.
133 * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
134 * than 1
135 */
136 public PriorityQueue(int initialCapacity,
137 Comparator<? super E> comparator) {
138 if (initialCapacity < 1)
139 throw new IllegalArgumentException();
140 this.queue = new Object[initialCapacity + 1];
141 this.comparator = comparator;
142 }
143
144 /**
145 * Common code to initialize underlying queue array across
146 * constructors below.
147 */
148 private void initializeArray(Collection<? extends E> c) {
149 int sz = c.size();
150 int initialCapacity = (int)Math.min((sz * 110L) / 100,
151 Integer.MAX_VALUE - 1);
152 if (initialCapacity < 1)
153 initialCapacity = 1;
154
155 this.queue = new Object[initialCapacity + 1];
156 }
157
158 /**
159 * Initially fill elements of the queue array under the
160 * knowledge that it is sorted or is another PQ, in which
161 * case we can just place the elements in the order presented.
162 */
163 private void fillFromSorted(Collection<? extends E> c) {
164 for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
165 queue[++size] = i.next();
166 }
167
168 /**
169 * Initially fill elements of the queue array that is not to our knowledge
170 * sorted, so we must rearrange the elements to guarantee the heap
171 * invariant.
172 */
173 private void fillFromUnsorted(Collection<? extends E> c) {
174 for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
175 queue[++size] = i.next();
176 heapify();
177 }
178
179 /**
180 * Creates a <tt>PriorityQueue</tt> containing the elements in the
181 * specified collection. The priority queue has an initial
182 * capacity of 110% of the size of the specified collection or 1
183 * if the collection is empty. If the specified collection is an
184 * instance of a {@link java.util.SortedSet} or is another
185 * <tt>PriorityQueue</tt>, the priority queue will be sorted
186 * according to the same comparator, or according to its elements'
187 * natural order if the collection is sorted according to its
188 * elements' natural order. Otherwise, the priority queue is
189 * ordered according to its elements' natural order.
190 *
191 * @param c the collection whose elements are to be placed
192 * into this priority queue.
193 * @throws ClassCastException if elements of the specified collection
194 * cannot be compared to one another according to the priority
195 * queue's ordering.
196 * @throws NullPointerException if <tt>c</tt> or any element within it
197 * is <tt>null</tt>
198 */
199 public PriorityQueue(Collection<? extends E> c) {
200 initializeArray(c);
201 if (c instanceof SortedSet) {
202 SortedSet<? extends E> s = (SortedSet<? extends E>)c;
203 comparator = (Comparator<? super E>)s.comparator();
204 fillFromSorted(s);
205 } else if (c instanceof PriorityQueue) {
206 PriorityQueue<? extends E> s = (PriorityQueue<? extends E>) c;
207 comparator = (Comparator<? super E>)s.comparator();
208 fillFromSorted(s);
209 } else {
210 comparator = null;
211 fillFromUnsorted(c);
212 }
213 }
214
215 /**
216 * Creates a <tt>PriorityQueue</tt> containing the elements in the
217 * specified collection. The priority queue has an initial
218 * capacity of 110% of the size of the specified collection or 1
219 * if the collection is empty. This priority queue will be sorted
220 * according to the same comparator as the given collection, or
221 * according to its elements' natural order if the collection is
222 * sorted according to its elements' natural order.
223 *
224 * @param c the collection whose elements are to be placed
225 * into this priority queue.
226 * @throws ClassCastException if elements of the specified collection
227 * cannot be compared to one another according to the priority
228 * queue's ordering.
229 * @throws NullPointerException if <tt>c</tt> or any element within it
230 * is <tt>null</tt>
231 */
232 public PriorityQueue(PriorityQueue<? extends E> c) {
233 initializeArray(c);
234 comparator = (Comparator<? super E>)c.comparator();
235 fillFromSorted(c);
236 }
237
238 /**
239 * Creates a <tt>PriorityQueue</tt> containing the elements in the
240 * specified collection. The priority queue has an initial
241 * capacity of 110% of the size of the specified collection or 1
242 * if the collection is empty. This priority queue will be sorted
243 * according to the same comparator as the given collection, or
244 * according to its elements' natural order if the collection is
245 * sorted according to its elements' natural order.
246 *
247 * @param c the collection whose elements are to be placed
248 * into this priority queue.
249 * @throws ClassCastException if elements of the specified collection
250 * cannot be compared to one another according to the priority
251 * queue's ordering.
252 * @throws NullPointerException if <tt>c</tt> or any element within it
253 * is <tt>null</tt>
254 */
255 public PriorityQueue(SortedSet<? extends E> c) {
256 initializeArray(c);
257 comparator = (Comparator<? super E>)c.comparator();
258 fillFromSorted(c);
259 }
260
261 /**
262 * Resize array, if necessary, to be able to hold given index
263 */
264 private void grow(int index) {
265 int newlen = queue.length;
266 if (index < newlen) // don't need to grow
267 return;
268 if (index == Integer.MAX_VALUE)
269 throw new OutOfMemoryError();
270 while (newlen <= index) {
271 if (newlen >= Integer.MAX_VALUE / 2) // avoid overflow
272 newlen = Integer.MAX_VALUE;
273 else
274 newlen <<= 2;
275 }
276 Object[] newQueue = new Object[newlen];
277 System.arraycopy(queue, 0, newQueue, 0, queue.length);
278 queue = newQueue;
279 }
280
281
282 /**
283 * Inserts the specified element into this priority queue.
284 *
285 * @return <tt>true</tt>
286 * @throws ClassCastException if the specified element cannot be compared
287 * with elements currently in the priority queue according
288 * to the priority queue's ordering.
289 * @throws NullPointerException if the specified element is <tt>null</tt>.
290 */
291 public boolean offer(E o) {
292 if (o == null)
293 throw new NullPointerException();
294 modCount++;
295 ++size;
296
297 // Grow backing store if necessary
298 if (size >= queue.length)
299 grow(size);
300
301 queue[size] = o;
302 fixUp(size);
303 return true;
304 }
305
306 public E peek() {
307 if (size == 0)
308 return null;
309 return (E) queue[1];
310 }
311
312 // Collection Methods - the first two override to update docs
313
314 /**
315 * Adds the specified element to this queue.
316 * @return <tt>true</tt> (as per the general contract of
317 * <tt>Collection.add</tt>).
318 *
319 * @throws NullPointerException if the specified element is <tt>null</tt>.
320 * @throws ClassCastException if the specified element cannot be compared
321 * with elements currently in the priority queue according
322 * to the priority queue's ordering.
323 */
324 public boolean add(E o) {
325 return offer(o);
326 }
327
328 /**
329 * Removes a single instance of the specified element from this
330 * collection, if it is present.
331 */
332 public boolean remove(Object o) {
333 if (o == null)
334 return false;
335
336 if (comparator == null) {
337 for (int i = 1; i <= size; i++) {
338 if (((Comparable<E>)queue[i]).compareTo((E)o) == 0) {
339 removeAt(i);
340 return true;
341 }
342 }
343 } else {
344 for (int i = 1; i <= size; i++) {
345 if (comparator.compare((E)queue[i], (E)o) == 0) {
346 removeAt(i);
347 return true;
348 }
349 }
350 }
351 return false;
352 }
353
354 /**
355 * Returns an iterator over the elements in this queue. The iterator
356 * does not return the elements in any particular order.
357 *
358 * @return an iterator over the elements in this queue.
359 */
360 public Iterator<E> iterator() {
361 return new Itr();
362 }
363
364 private class Itr implements Iterator<E> {
365
366 /**
367 * Index (into queue array) of element to be returned by
368 * subsequent call to next.
369 */
370 private int cursor = 1;
371
372 /**
373 * Index of element returned by most recent call to next,
374 * unless that element came from the forgetMeNot list.
375 * Reset to 0 if element is deleted by a call to remove.
376 */
377 private int lastRet = 0;
378
379 /**
380 * The modCount value that the iterator believes that the backing
381 * List should have. If this expectation is violated, the iterator
382 * has detected concurrent modification.
383 */
384 private int expectedModCount = modCount;
385
386 /**
387 * A list of elements that were moved from the unvisited portion of
388 * the heap into the visited portion as a result of "unlucky" element
389 * removals during the iteration. (Unlucky element removals are those
390 * that require a fixup instead of a fixdown.) We must visit all of
391 * the elements in this list to complete the iteration. We do this
392 * after we've completed the "normal" iteration.
393 *
394 * We expect that most iterations, even those involving removals,
395 * will not use need to store elements in this field.
396 */
397 private ArrayList<E> forgetMeNot = null;
398
399 /**
400 * Element returned by the most recent call to next iff that
401 * element was drawn from the forgetMeNot list.
402 */
403 private Object lastRetElt = null;
404
405 public boolean hasNext() {
406 return cursor <= size || forgetMeNot != null;
407 }
408
409 public E next() {
410 checkForComodification();
411 E result;
412 if (cursor <= size) {
413 result = (E) queue[cursor];
414 lastRet = cursor++;
415 }
416 else if (forgetMeNot == null)
417 throw new NoSuchElementException();
418 else {
419 int remaining = forgetMeNot.size();
420 result = forgetMeNot.remove(remaining - 1);
421 if (remaining == 1)
422 forgetMeNot = null;
423 lastRet = 0;
424 lastRetElt = result;
425 }
426 return result;
427 }
428
429 public void remove() {
430 checkForComodification();
431
432 if (lastRet != 0) {
433 E moved = PriorityQueue.this.removeAt(lastRet);
434 lastRet = 0;
435 if (moved == null) {
436 cursor--;
437 } else {
438 if (forgetMeNot == null)
439 forgetMeNot = new ArrayList<E>();
440 forgetMeNot.add(moved);
441 }
442 } else if (lastRetElt != null) {
443 PriorityQueue.this.remove(lastRetElt);
444 lastRetElt = null;
445 } else {
446 throw new IllegalStateException();
447 }
448
449 expectedModCount = modCount;
450 }
451
452 final void checkForComodification() {
453 if (modCount != expectedModCount)
454 throw new ConcurrentModificationException();
455 }
456 }
457
458 public int size() {
459 return size;
460 }
461
462 /**
463 * Removes all elements from the priority queue.
464 * The queue will be empty after this call returns.
465 */
466 public void clear() {
467 modCount++;
468
469 // Null out element references to prevent memory leak
470 for (int i=1; i<=size; i++)
471 queue[i] = null;
472
473 size = 0;
474 }
475
476 public E poll() {
477 if (size == 0)
478 return null;
479 modCount++;
480
481 E result = (E) queue[1];
482 queue[1] = queue[size];
483 queue[size--] = null; // Drop extra ref to prevent memory leak
484 if (size > 1)
485 fixDown(1);
486
487 return result;
488 }
489
490 /**
491 * Removes and returns the ith element from queue. (Recall that queue
492 * is one-based, so 1 <= i <= size.)
493 *
494 * Normally this method leaves the elements at positions from 1 up to i-1,
495 * inclusive, untouched. Under these circumstances, it returns null.
496 * Occasionally, in order to maintain the heap invariant, it must move
497 * the last element of the list to some index in the range [2, i-1],
498 * and move the element previously at position (i/2) to position i.
499 * Under these circumstances, this method returns the element that was
500 * previously at the end of the list and is now at some position between
501 * 2 and i-1 inclusive.
502 */
503 private E removeAt(int i) {
504 assert i > 0 && i <= size;
505 modCount++;
506
507 E moved = (E) queue[size];
508 queue[i] = moved;
509 queue[size--] = null; // Drop extra ref to prevent memory leak
510 if (i <= size) {
511 fixDown(i);
512 if (queue[i] == moved) {
513 fixUp(i);
514 if (queue[i] != moved)
515 return moved;
516 }
517 }
518 return null;
519 }
520
521 /**
522 * Establishes the heap invariant (described above) assuming the heap
523 * satisfies the invariant except possibly for the leaf-node indexed by k
524 * (which may have a nextExecutionTime less than its parent's).
525 *
526 * This method functions by "promoting" queue[k] up the hierarchy
527 * (by swapping it with its parent) repeatedly until queue[k]
528 * is greater than or equal to its parent.
529 */
530 private void fixUp(int k) {
531 if (comparator == null) {
532 while (k > 1) {
533 int j = k >> 1;
534 if (((Comparable<E>)queue[j]).compareTo((E)queue[k]) <= 0)
535 break;
536 Object tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
537 k = j;
538 }
539 } else {
540 while (k > 1) {
541 int j = k >>> 1;
542 if (comparator.compare((E)queue[j], (E)queue[k]) <= 0)
543 break;
544 Object tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
545 k = j;
546 }
547 }
548 }
549
550 /**
551 * Establishes the heap invariant (described above) in the subtree
552 * rooted at k, which is assumed to satisfy the heap invariant except
553 * possibly for node k itself (which may be greater than its children).
554 *
555 * This method functions by "demoting" queue[k] down the hierarchy
556 * (by swapping it with its smaller child) repeatedly until queue[k]
557 * is less than or equal to its children.
558 */
559 private void fixDown(int k) {
560 int j;
561 if (comparator == null) {
562 while ((j = k << 1) <= size && (j > 0)) {
563 if (j<size &&
564 ((Comparable<E>)queue[j]).compareTo((E)queue[j+1]) > 0)
565 j++; // j indexes smallest kid
566
567 if (((Comparable<E>)queue[k]).compareTo((E)queue[j]) <= 0)
568 break;
569 Object tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
570 k = j;
571 }
572 } else {
573 while ((j = k << 1) <= size && (j > 0)) {
574 if (j<size &&
575 comparator.compare((E)queue[j], (E)queue[j+1]) > 0)
576 j++; // j indexes smallest kid
577 if (comparator.compare((E)queue[k], (E)queue[j]) <= 0)
578 break;
579 Object tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
580 k = j;
581 }
582 }
583 }
584
585 /**
586 * Establishes the heap invariant (described above) in the entire tree,
587 * assuming nothing about the order of the elements prior to the call.
588 */
589 private void heapify() {
590 for (int i = size/2; i >= 1; i--)
591 fixDown(i);
592 }
593
594 /**
595 * Returns the comparator used to order this collection, or <tt>null</tt>
596 * if this collection is sorted according to its elements natural ordering
597 * (using <tt>Comparable</tt>).
598 *
599 * @return the comparator used to order this collection, or <tt>null</tt>
600 * if this collection is sorted according to its elements natural ordering.
601 */
602 public Comparator<? super E> comparator() {
603 return comparator;
604 }
605
606 /**
607 * Save the state of the instance to a stream (that
608 * is, serialize it).
609 *
610 * @serialData The length of the array backing the instance is
611 * emitted (int), followed by all of its elements (each an
612 * <tt>Object</tt>) in the proper order.
613 * @param s the stream
614 */
615 private void writeObject(java.io.ObjectOutputStream s)
616 throws java.io.IOException{
617 // Write out element count, and any hidden stuff
618 s.defaultWriteObject();
619
620 // Write out array length
621 s.writeInt(queue.length);
622
623 // Write out all elements in the proper order.
624 for (int i=1; i<=size; i++)
625 s.writeObject(queue[i]);
626 }
627
628 /**
629 * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
630 * deserialize it).
631 * @param s the stream
632 */
633 private void readObject(java.io.ObjectInputStream s)
634 throws java.io.IOException, ClassNotFoundException {
635 // Read in size, and any hidden stuff
636 s.defaultReadObject();
637
638 // Read in array length and allocate array
639 int arrayLength = s.readInt();
640 queue = new Object[arrayLength];
641
642 // Read in all elements in the proper order.
643 for (int i=1; i<=size; i++)
644 queue[i] = (E) s.readObject();
645 }
646
647 }