ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/PriorityQueue.java
Revision: 1.29
Committed: Sun Aug 24 23:31:53 2003 UTC (20 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.28: +12 -0 lines
Log Message:
Mention at top that traversal not ordered

File Contents

# User Rev Content
1 tim 1.2 package java.util;
2 tim 1.1
3     /**
4 dholmes 1.23 * An unbounded priority {@linkplain Queue queue} based on a priority heap.
5     * This queue orders
6 brian 1.6 * elements according to an order specified at construction time, which is
7 tim 1.19 * specified in the same manner as {@link java.util.TreeSet} and
8 dholmes 1.18 * {@link java.util.TreeMap}: elements are ordered
9 tim 1.2 * either according to their <i>natural order</i> (see {@link Comparable}), or
10 tim 1.19 * according to a {@link java.util.Comparator}, depending on which
11 dholmes 1.18 * constructor is used.
12 tim 1.19 * <p>The <em>head</em> of this queue is the <em>least</em> element with
13     * respect to the specified ordering.
14 dholmes 1.18 * If multiple elements are tied for least value, the
15 tim 1.14 * head is one of those elements. A priority queue does not permit
16 dholmes 1.11 * <tt>null</tt> elements.
17 tim 1.14 *
18 dholmes 1.11 * <p>The {@link #remove()} and {@link #poll()} methods remove and
19     * return the head of the queue.
20     *
21     * <p>The {@link #element()} and {@link #peek()} methods return, but do
22     * not delete, the head of the queue.
23 tim 1.2 *
24 dl 1.7 * <p>A priority queue has a <i>capacity</i>. The capacity is the
25     * size of the array used internally to store the elements on the
26 dholmes 1.20 * queue.
27 dholmes 1.18 * It is always at least as large as the queue size. As
28 dl 1.7 * elements are added to a priority queue, its capacity grows
29     * automatically. The details of the growth policy are not specified.
30 tim 1.2 *
31 dl 1.29 * <p>The Iterator provided in method {@link #iterator()} is <em>not</em>
32     * guaranteed to traverse the elements of the PriorityQueue in any
33     * particular order. If you need ordered traversal, consider using
34     * <tt>Arrays.sort(pq.toArray())</tt>.
35     *
36     * <p> <strong>Note that this implementation is not synchronized.</strong>
37     * Multiple threads should not access a <tt>PriorityQueue</tt>
38     * instance concurrently if any of the threads modifies the list
39     * structurally. Instead, use the thread-safe {@link
40     * java.util.concurrent.BlockingPriorityQueue} class.
41     *
42     *
43 dholmes 1.11 * <p>Implementation note: this implementation provides O(log(n)) time
44     * for the insertion methods (<tt>offer</tt>, <tt>poll</tt>,
45     * <tt>remove()</tt> and <tt>add</tt>) methods; linear time for the
46     * <tt>remove(Object)</tt> and <tt>contains(Object)</tt> methods; and
47     * constant time for the retrieval methods (<tt>peek</tt>,
48     * <tt>element</tt>, and <tt>size</tt>).
49 tim 1.2 *
50     * <p>This class is a member of the
51     * <a href="{@docRoot}/../guide/collections/index.html">
52     * Java Collections Framework</a>.
53 dl 1.7 * @since 1.5
54     * @author Josh Bloch
55 tim 1.2 */
56     public class PriorityQueue<E> extends AbstractQueue<E>
57 dl 1.22 implements Queue<E>, java.io.Serializable {
58 dholmes 1.11
59 tim 1.2 private static final int DEFAULT_INITIAL_CAPACITY = 11;
60 tim 1.1
61 tim 1.2 /**
62     * Priority queue represented as a balanced binary heap: the two children
63     * of queue[n] are queue[2*n] and queue[2*n + 1]. The priority queue is
64     * ordered by comparator, or by the elements' natural ordering, if
65 brian 1.6 * comparator is null: For each node n in the heap and each descendant d
66     * of n, n <= d.
67 tim 1.2 *
68 brian 1.6 * The element with the lowest value is in queue[1], assuming the queue is
69     * nonempty. (A one-based array is used in preference to the traditional
70     * zero-based array to simplify parent and child calculations.)
71 tim 1.2 *
72     * queue.length must be >= 2, even if size == 0.
73     */
74 tim 1.16 private transient Object[] queue;
75 tim 1.1
76 tim 1.2 /**
77     * The number of elements in the priority queue.
78     */
79     private int size = 0;
80 tim 1.1
81 tim 1.2 /**
82     * The comparator, or null if priority queue uses elements'
83     * natural ordering.
84     */
85 tim 1.16 private final Comparator<? super E> comparator;
86 tim 1.2
87     /**
88     * The number of times this priority queue has been
89     * <i>structurally modified</i>. See AbstractList for gory details.
90     */
91 dl 1.5 private transient int modCount = 0;
92 tim 1.2
93     /**
94 dholmes 1.21 * Creates a <tt>PriorityQueue</tt> with the default initial capacity
95 dl 1.7 * (11) that orders its elements according to their natural
96 tim 1.24 * ordering (using <tt>Comparable</tt>).
97 tim 1.2 */
98     public PriorityQueue() {
99 dholmes 1.11 this(DEFAULT_INITIAL_CAPACITY, null);
100 tim 1.1 }
101 tim 1.2
102     /**
103 dholmes 1.21 * Creates a <tt>PriorityQueue</tt> with the specified initial capacity
104 dl 1.7 * that orders its elements according to their natural ordering
105 tim 1.24 * (using <tt>Comparable</tt>).
106 tim 1.2 *
107     * @param initialCapacity the initial capacity for this priority queue.
108 dholmes 1.23 * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
109     * than 1
110 tim 1.2 */
111     public PriorityQueue(int initialCapacity) {
112     this(initialCapacity, null);
113 tim 1.1 }
114 tim 1.2
115     /**
116 dholmes 1.21 * Creates a <tt>PriorityQueue</tt> with the specified initial capacity
117 tim 1.2 * that orders its elements according to the specified comparator.
118     *
119     * @param initialCapacity the initial capacity for this priority queue.
120     * @param comparator the comparator used to order this priority queue.
121 dholmes 1.11 * If <tt>null</tt> then the order depends on the elements' natural
122     * ordering.
123 dholmes 1.15 * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
124     * than 1
125 tim 1.2 */
126 dholmes 1.23 public PriorityQueue(int initialCapacity,
127     Comparator<? super E> comparator) {
128 tim 1.2 if (initialCapacity < 1)
129 dholmes 1.15 throw new IllegalArgumentException();
130 tim 1.16 this.queue = new Object[initialCapacity + 1];
131 tim 1.2 this.comparator = comparator;
132 tim 1.1 }
133    
134 tim 1.2 /**
135 dl 1.22 * Common code to initialize underlying queue array across
136     * constructors below.
137     */
138     private void initializeArray(Collection<? extends E> c) {
139     int sz = c.size();
140     int initialCapacity = (int)Math.min((sz * 110L) / 100,
141     Integer.MAX_VALUE - 1);
142     if (initialCapacity < 1)
143     initialCapacity = 1;
144    
145     this.queue = new Object[initialCapacity + 1];
146     }
147    
148     /**
149     * Initially fill elements of the queue array under the
150     * knowledge that it is sorted or is another PQ, in which
151     * case we can just place the elements without fixups.
152     */
153     private void fillFromSorted(Collection<? extends E> c) {
154     for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
155     queue[++size] = i.next();
156     }
157    
158    
159     /**
160     * Initially fill elements of the queue array that is
161     * not to our knowledge sorted, so we must add them
162     * one by one.
163     */
164     private void fillFromUnsorted(Collection<? extends E> c) {
165     for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
166     add(i.next());
167     }
168    
169     /**
170     * Creates a <tt>PriorityQueue</tt> containing the elements in the
171     * specified collection. The priority queue has an initial
172     * capacity of 110% of the size of the specified collection or 1
173     * if the collection is empty. If the specified collection is an
174 tim 1.25 * instance of a {@link java.util.SortedSet} or is another
175 dl 1.22 * <tt>PriorityQueue</tt>, the priority queue will be sorted
176     * according to the same comparator, or according to its elements'
177     * natural order if the collection is sorted according to its
178     * elements' natural order. Otherwise, the priority queue is
179     * ordered according to its elements' natural order.
180 tim 1.2 *
181 dholmes 1.15 * @param c the collection whose elements are to be placed
182 tim 1.2 * into this priority queue.
183     * @throws ClassCastException if elements of the specified collection
184     * cannot be compared to one another according to the priority
185     * queue's ordering.
186 dholmes 1.15 * @throws NullPointerException if <tt>c</tt> or any element within it
187     * is <tt>null</tt>
188 tim 1.2 */
189 tim 1.16 public PriorityQueue(Collection<? extends E> c) {
190 dl 1.22 initializeArray(c);
191 dl 1.27 if (c instanceof SortedSet) {
192 dl 1.28 // @fixme double-cast workaround for compiler
193     SortedSet<? extends E> s = (SortedSet<? extends E>) (SortedSet)c;
194 dl 1.22 comparator = (Comparator<? super E>)s.comparator();
195     fillFromSorted(s);
196 dl 1.27 } else if (c instanceof PriorityQueue) {
197 dl 1.22 PriorityQueue<? extends E> s = (PriorityQueue<? extends E>) c;
198     comparator = (Comparator<? super E>)s.comparator();
199     fillFromSorted(s);
200 tim 1.26 } else {
201 tim 1.2 comparator = null;
202 dl 1.22 fillFromUnsorted(c);
203 tim 1.2 }
204 dl 1.22 }
205    
206     /**
207     * Creates a <tt>PriorityQueue</tt> containing the elements in the
208     * specified collection. The priority queue has an initial
209     * capacity of 110% of the size of the specified collection or 1
210     * if the collection is empty. This priority queue will be sorted
211     * according to the same comparator as the given collection, or
212     * according to its elements' natural order if the collection is
213     * sorted according to its elements' natural order.
214     *
215     * @param c the collection whose elements are to be placed
216     * into this priority queue.
217     * @throws ClassCastException if elements of the specified collection
218     * cannot be compared to one another according to the priority
219     * queue's ordering.
220     * @throws NullPointerException if <tt>c</tt> or any element within it
221     * is <tt>null</tt>
222     */
223     public PriorityQueue(PriorityQueue<? extends E> c) {
224     initializeArray(c);
225     comparator = (Comparator<? super E>)c.comparator();
226     fillFromSorted(c);
227     }
228 dholmes 1.18
229 dl 1.22 /**
230     * Creates a <tt>PriorityQueue</tt> containing the elements in the
231     * specified collection. The priority queue has an initial
232     * capacity of 110% of the size of the specified collection or 1
233     * if the collection is empty. This priority queue will be sorted
234     * according to the same comparator as the given collection, or
235     * according to its elements' natural order if the collection is
236     * sorted according to its elements' natural order.
237     *
238     * @param c the collection whose elements are to be placed
239     * into this priority queue.
240     * @throws ClassCastException if elements of the specified collection
241     * cannot be compared to one another according to the priority
242     * queue's ordering.
243     * @throws NullPointerException if <tt>c</tt> or any element within it
244     * is <tt>null</tt>
245     */
246     public PriorityQueue(SortedSet<? extends E> c) {
247     initializeArray(c);
248     comparator = (Comparator<? super E>)c.comparator();
249     fillFromSorted(c);
250 tim 1.1 }
251    
252 dl 1.22 /**
253     * Resize array, if necessary, to be able to hold given index
254     */
255     private void grow(int index) {
256     int newlen = queue.length;
257     if (index < newlen) // don't need to grow
258     return;
259     if (index == Integer.MAX_VALUE)
260     throw new OutOfMemoryError();
261     while (newlen <= index) {
262     if (newlen >= Integer.MAX_VALUE / 2) // avoid overflow
263     newlen = Integer.MAX_VALUE;
264     else
265     newlen <<= 2;
266     }
267     Object[] newQueue = new Object[newlen];
268     System.arraycopy(queue, 0, newQueue, 0, queue.length);
269     queue = newQueue;
270     }
271    
272 tim 1.2 // Queue Methods
273    
274 dholmes 1.23
275    
276 tim 1.2 /**
277 dholmes 1.11 * Add the specified element to this priority queue.
278 tim 1.2 *
279 dholmes 1.11 * @return <tt>true</tt>
280     * @throws ClassCastException if the specified element cannot be compared
281     * with elements currently in the priority queue according
282     * to the priority queue's ordering.
283 dholmes 1.18 * @throws NullPointerException if the specified element is <tt>null</tt>.
284 tim 1.2 */
285 dholmes 1.18 public boolean offer(E o) {
286     if (o == null)
287 dholmes 1.11 throw new NullPointerException();
288     modCount++;
289     ++size;
290    
291     // Grow backing store if necessary
292 dl 1.22 if (size >= queue.length)
293     grow(size);
294 dholmes 1.11
295 dholmes 1.18 queue[size] = o;
296 dholmes 1.11 fixUp(size);
297     return true;
298     }
299    
300 tim 1.1 public E poll() {
301 tim 1.2 if (size == 0)
302     return null;
303 tim 1.16 return (E) remove(1);
304 tim 1.1 }
305 tim 1.2
306 tim 1.1 public E peek() {
307 tim 1.16 return (E) queue[1];
308 tim 1.1 }
309    
310 dholmes 1.23 // Collection Methods - the first two override to update docs
311 dholmes 1.11
312     /**
313 dholmes 1.23 * Adds the specified element to this queue.
314     * @return <tt>true</tt> (as per the general contract of
315     * <tt>Collection.add</tt>).
316     *
317     * @throws NullPointerException {@inheritDoc}
318 dholmes 1.15 * @throws ClassCastException if the specified element cannot be compared
319     * with elements currently in the priority queue according
320     * to the priority queue's ordering.
321 dholmes 1.11 */
322 dholmes 1.18 public boolean add(E o) {
323     return super.add(o);
324 dholmes 1.11 }
325    
326 dholmes 1.23
327 tim 1.14 /**
328 dholmes 1.23 * Adds all of the elements in the specified collection to this queue.
329     * The behavior of this operation is undefined if
330     * the specified collection is modified while the operation is in
331     * progress. (This implies that the behavior of this call is undefined if
332     * the specified collection is this queue, and this queue is nonempty.)
333     * <p>
334     * This implementation iterates over the specified collection, and adds
335     * each object returned by the iterator to this collection, in turn.
336     * @throws NullPointerException {@inheritDoc}
337 dholmes 1.15 * @throws ClassCastException if any element cannot be compared
338     * with elements currently in the priority queue according
339     * to the priority queue's ordering.
340 tim 1.14 */
341     public boolean addAll(Collection<? extends E> c) {
342     return super.addAll(c);
343     }
344 dholmes 1.11
345 dholmes 1.23
346     /**
347     * Removes a single instance of the specified element from this
348     * queue, if it is present. More formally,
349     * removes an element <tt>e</tt> such that <tt>(o==null ? e==null :
350     * o.equals(e))</tt>, if the queue contains one or more such
351     * elements. Returns <tt>true</tt> if the queue contained the
352     * specified element (or equivalently, if the queue changed as a
353     * result of the call).
354     *
355     * <p>This implementation iterates over the queue looking for the
356     * specified element. If it finds the element, it removes the element
357     * from the queue using the iterator's remove method.<p>
358     *
359     */
360 dl 1.12 public boolean remove(Object o) {
361 dholmes 1.11 if (o == null)
362 dholmes 1.15 return false;
363 tim 1.2
364     if (comparator == null) {
365     for (int i = 1; i <= size; i++) {
366 tim 1.16 if (((Comparable<E>)queue[i]).compareTo((E)o) == 0) {
367 tim 1.2 remove(i);
368     return true;
369     }
370     }
371     } else {
372     for (int i = 1; i <= size; i++) {
373 tim 1.16 if (comparator.compare((E)queue[i], (E)o) == 0) {
374 tim 1.2 remove(i);
375     return true;
376     }
377     }
378     }
379 tim 1.1 return false;
380     }
381 tim 1.2
382 dholmes 1.23 /**
383     * Returns an iterator over the elements in this queue. The iterator
384     * does not return the elements in any particular order.
385     *
386     * @return an iterator over the elements in this queue.
387     */
388 tim 1.2 public Iterator<E> iterator() {
389 dl 1.7 return new Itr();
390 tim 1.2 }
391    
392     private class Itr implements Iterator<E> {
393 dl 1.7 /**
394     * Index (into queue array) of element to be returned by
395 tim 1.2 * subsequent call to next.
396 dl 1.7 */
397     private int cursor = 1;
398 tim 1.2
399 dl 1.7 /**
400     * Index of element returned by most recent call to next or
401     * previous. Reset to 0 if this element is deleted by a call
402     * to remove.
403     */
404     private int lastRet = 0;
405    
406     /**
407     * The modCount value that the iterator believes that the backing
408     * List should have. If this expectation is violated, the iterator
409     * has detected concurrent modification.
410     */
411     private int expectedModCount = modCount;
412 tim 1.2
413 dl 1.7 public boolean hasNext() {
414     return cursor <= size;
415     }
416    
417     public E next() {
418 tim 1.2 checkForComodification();
419     if (cursor > size)
420 dl 1.7 throw new NoSuchElementException();
421 tim 1.16 E result = (E) queue[cursor];
422 tim 1.2 lastRet = cursor++;
423     return result;
424 dl 1.7 }
425 tim 1.2
426 dl 1.7 public void remove() {
427     if (lastRet == 0)
428     throw new IllegalStateException();
429 tim 1.2 checkForComodification();
430    
431     PriorityQueue.this.remove(lastRet);
432     if (lastRet < cursor)
433     cursor--;
434     lastRet = 0;
435     expectedModCount = modCount;
436 dl 1.7 }
437 tim 1.2
438 dl 1.7 final void checkForComodification() {
439     if (modCount != expectedModCount)
440     throw new ConcurrentModificationException();
441     }
442 tim 1.2 }
443    
444 tim 1.1 public int size() {
445 tim 1.2 return size;
446 tim 1.1 }
447 tim 1.2
448     /**
449     * Remove all elements from the priority queue.
450     */
451     public void clear() {
452     modCount++;
453    
454     // Null out element references to prevent memory leak
455     for (int i=1; i<=size; i++)
456     queue[i] = null;
457    
458     size = 0;
459     }
460    
461     /**
462     * Removes and returns the ith element from queue. Recall
463     * that queue is one-based, so 1 <= i <= size.
464     *
465     * XXX: Could further special-case i==size, but is it worth it?
466     * XXX: Could special-case i==0, but is it worth it?
467     */
468     private E remove(int i) {
469     assert i <= size;
470     modCount++;
471    
472 tim 1.16 E result = (E) queue[i];
473 tim 1.2 queue[i] = queue[size];
474     queue[size--] = null; // Drop extra ref to prevent memory leak
475     if (i <= size)
476     fixDown(i);
477     return result;
478 tim 1.1 }
479    
480 tim 1.2 /**
481     * Establishes the heap invariant (described above) assuming the heap
482     * satisfies the invariant except possibly for the leaf-node indexed by k
483     * (which may have a nextExecutionTime less than its parent's).
484     *
485     * This method functions by "promoting" queue[k] up the hierarchy
486     * (by swapping it with its parent) repeatedly until queue[k]
487     * is greater than or equal to its parent.
488     */
489     private void fixUp(int k) {
490     if (comparator == null) {
491     while (k > 1) {
492     int j = k >> 1;
493 tim 1.16 if (((Comparable<E>)queue[j]).compareTo((E)queue[k]) <= 0)
494 tim 1.2 break;
495 tim 1.16 Object tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
496 tim 1.2 k = j;
497     }
498     } else {
499     while (k > 1) {
500     int j = k >> 1;
501 tim 1.16 if (comparator.compare((E)queue[j], (E)queue[k]) <= 0)
502 tim 1.2 break;
503 tim 1.16 Object tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
504 tim 1.2 k = j;
505     }
506     }
507     }
508    
509     /**
510     * Establishes the heap invariant (described above) in the subtree
511     * rooted at k, which is assumed to satisfy the heap invariant except
512     * possibly for node k itself (which may be greater than its children).
513     *
514     * This method functions by "demoting" queue[k] down the hierarchy
515     * (by swapping it with its smaller child) repeatedly until queue[k]
516     * is less than or equal to its children.
517     */
518     private void fixDown(int k) {
519     int j;
520     if (comparator == null) {
521     while ((j = k << 1) <= size) {
522 tim 1.16 if (j<size && ((Comparable<E>)queue[j]).compareTo((E)queue[j+1]) > 0)
523 tim 1.2 j++; // j indexes smallest kid
524 tim 1.16 if (((Comparable<E>)queue[k]).compareTo((E)queue[j]) <= 0)
525 tim 1.2 break;
526 tim 1.16 Object tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
527 tim 1.2 k = j;
528     }
529     } else {
530     while ((j = k << 1) <= size) {
531 tim 1.16 if (j < size && comparator.compare((E)queue[j], (E)queue[j+1]) > 0)
532 tim 1.2 j++; // j indexes smallest kid
533 tim 1.16 if (comparator.compare((E)queue[k], (E)queue[j]) <= 0)
534 tim 1.2 break;
535 tim 1.16 Object tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
536 tim 1.2 k = j;
537     }
538     }
539     }
540    
541 dholmes 1.23
542     /**
543     * Returns the comparator used to order this collection, or <tt>null</tt>
544     * if this collection is sorted according to its elements natural ordering
545 tim 1.24 * (using <tt>Comparable</tt>).
546 dholmes 1.23 *
547     * @return the comparator used to order this collection, or <tt>null</tt>
548     * if this collection is sorted according to its elements natural ordering.
549     */
550 tim 1.16 public Comparator<? super E> comparator() {
551 tim 1.2 return comparator;
552     }
553 dl 1.5
554     /**
555     * Save the state of the instance to a stream (that
556     * is, serialize it).
557     *
558     * @serialData The length of the array backing the instance is
559     * emitted (int), followed by all of its elements (each an
560     * <tt>Object</tt>) in the proper order.
561 dl 1.7 * @param s the stream
562 dl 1.5 */
563 dl 1.22 private void writeObject(java.io.ObjectOutputStream s)
564 dl 1.5 throws java.io.IOException{
565 dl 1.7 // Write out element count, and any hidden stuff
566     s.defaultWriteObject();
567 dl 1.5
568     // Write out array length
569     s.writeInt(queue.length);
570    
571 dl 1.7 // Write out all elements in the proper order.
572     for (int i=0; i<size; i++)
573 dl 1.5 s.writeObject(queue[i]);
574     }
575    
576     /**
577     * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
578     * deserialize it).
579 dl 1.7 * @param s the stream
580 dl 1.5 */
581 dl 1.22 private void readObject(java.io.ObjectInputStream s)
582 dl 1.5 throws java.io.IOException, ClassNotFoundException {
583 dl 1.7 // Read in size, and any hidden stuff
584     s.defaultReadObject();
585 dl 1.5
586     // Read in array length and allocate array
587     int arrayLength = s.readInt();
588 tim 1.16 queue = new Object[arrayLength];
589 dl 1.5
590 dl 1.7 // Read in all elements in the proper order.
591     for (int i=0; i<size; i++)
592 tim 1.16 queue[i] = s.readObject();
593 dl 1.5 }
594    
595 tim 1.1 }
596 dholmes 1.11