ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/PriorityQueue.java
Revision: 1.28
Committed: Wed Aug 13 14:11:59 2003 UTC (20 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.27: +2 -1 lines
Log Message:
Added raw cast as workaround for compiler bug

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