ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/PriorityQueue.java
Revision: 1.6
Committed: Mon Jun 23 02:26:15 2003 UTC (20 years, 10 months ago) by brian
Branch: MAIN
Changes since 1.5: +25 -24 lines
Log Message:
Partial javadoc pass

File Contents

# User Rev Content
1 tim 1.2 package java.util;
2 tim 1.1
3     /**
4 tim 1.2 * An unbounded priority queue based on a priority heap. This queue orders
5 brian 1.6 * elements according to an order specified at construction time, which is
6     * specified in the same manner as {@link TreeSet} and {@link TreeMap}: elements are ordered
7 tim 1.2 * either according to their <i>natural order</i> (see {@link Comparable}), or
8     * according to a {@link Comparator}, depending on which constructor is used.
9     * The {@link #peek}, {@link #poll}, and {@link #remove} methods return the
10     * minimal element with respect to the specified ordering. If multiple
11 brian 1.6 * elements are tied for least value, no guarantees are made as to
12     * which of these elements is returned.
13 tim 1.2 *
14 brian 1.6 * <p>A priority queue has a <i>capacity</i>. The capacity is the size of
15     * the array used internally to store the elements on the queue. It is always at least
16     * as large as the queue size. As elements are added to a priority queue,
17 tim 1.2 * its capacity grows automatically. The details of the growth policy are not
18     * specified.
19     *
20     *<p>Implementation note: this implementation provides O(log(n)) time for
21 brian 1.6 * the insertion methods (<tt>offer</tt>, <tt>poll</tt>, <tt>remove()</tt> and <tt>add</tt>)
22 tim 1.2 * methods; linear time for the <tt>remove(Object)</tt> and
23 brian 1.6 * <tt>contains(Object)</tt> methods; and constant time for the retrieval methods (<tt>peek</tt>,
24     * <tt>element</tt>, and <tt>size</tt>).
25 tim 1.2 *
26     * <p>This class is a member of the
27     * <a href="{@docRoot}/../guide/collections/index.html">
28     * Java Collections Framework</a>.
29     */
30     public class PriorityQueue<E> extends AbstractQueue<E>
31     implements Queue<E>
32     {
33     private static final int DEFAULT_INITIAL_CAPACITY = 11;
34 tim 1.1
35 tim 1.2 /**
36     * Priority queue represented as a balanced binary heap: the two children
37     * of queue[n] are queue[2*n] and queue[2*n + 1]. The priority queue is
38     * ordered by comparator, or by the elements' natural ordering, if
39 brian 1.6 * comparator is null: For each node n in the heap and each descendant d
40     * of n, n <= d.
41 tim 1.2 *
42 brian 1.6 * The element with the lowest value is in queue[1], assuming the queue is
43     * nonempty. (A one-based array is used in preference to the traditional
44     * zero-based array to simplify parent and child calculations.)
45 tim 1.2 *
46     * queue.length must be >= 2, even if size == 0.
47     */
48 dl 1.5 private transient E[] queue;
49 tim 1.1
50 tim 1.2 /**
51     * The number of elements in the priority queue.
52     */
53     private int size = 0;
54 tim 1.1
55 tim 1.2 /**
56     * The comparator, or null if priority queue uses elements'
57     * natural ordering.
58     */
59     private final Comparator<E> comparator;
60    
61     /**
62     * The number of times this priority queue has been
63     * <i>structurally modified</i>. See AbstractList for gory details.
64     */
65 dl 1.5 private transient int modCount = 0;
66 tim 1.2
67     /**
68     * Create a new priority queue with the default initial capacity (11)
69 brian 1.6 * that orders its elements according to their natural ordering (using <tt>Comparable</tt>.)
70 tim 1.2 */
71     public PriorityQueue() {
72     this(DEFAULT_INITIAL_CAPACITY);
73 tim 1.1 }
74 tim 1.2
75     /**
76     * Create a new priority queue with the specified initial capacity
77 brian 1.6 * that orders its elements according to their natural ordering (using <tt>Comparable</tt>.)
78 tim 1.2 *
79     * @param initialCapacity the initial capacity for this priority queue.
80     */
81     public PriorityQueue(int initialCapacity) {
82     this(initialCapacity, null);
83 tim 1.1 }
84 tim 1.2
85     /**
86     * Create a new priority queue with the specified initial capacity (11)
87     * that orders its elements according to the specified comparator.
88     *
89     * @param initialCapacity the initial capacity for this priority queue.
90     * @param comparator the comparator used to order this priority queue.
91     */
92     public PriorityQueue(int initialCapacity, Comparator<E> comparator) {
93     if (initialCapacity < 1)
94     initialCapacity = 1;
95     queue = new E[initialCapacity + 1];
96     this.comparator = comparator;
97 tim 1.1 }
98    
99 tim 1.2 /**
100     * Create a new priority queue containing the elements in the specified
101     * collection. The priority queue has an initial capacity of 110% of the
102     * size of the specified collection. If the specified collection
103     * implements the {@link Sorted} interface, the priority queue will be
104     * sorted according to the same comparator, or according to its elements'
105     * natural order if the collection is sorted according to its elements'
106 brian 1.6 * natural order. If the specified collection does not implement
107     * <tt>Sorted</tt>, the priority queue is ordered according to
108 tim 1.2 * its elements' natural order.
109     *
110     * @param initialElements the collection whose elements are to be placed
111     * into this priority queue.
112     * @throws ClassCastException if elements of the specified collection
113     * cannot be compared to one another according to the priority
114     * queue's ordering.
115     * @throws NullPointerException if the specified collection or an
116     * element of the specified collection is <tt>null</tt>.
117     */
118     public PriorityQueue(Collection<E> initialElements) {
119     int sz = initialElements.size();
120     int initialCapacity = (int)Math.min((sz * 110L) / 100,
121     Integer.MAX_VALUE - 1);
122     if (initialCapacity < 1)
123     initialCapacity = 1;
124     queue = new E[initialCapacity + 1];
125    
126 dl 1.5 /* Commented out to compile with generics compiler
127    
128 tim 1.2 if (initialElements instanceof Sorted) {
129     comparator = ((Sorted)initialElements).comparator();
130     for (Iterator<E> i = initialElements.iterator(); i.hasNext(); )
131     queue[++size] = i.next();
132     } else {
133 dl 1.5 */
134     {
135 tim 1.2 comparator = null;
136     for (Iterator<E> i = initialElements.iterator(); i.hasNext(); )
137     add(i.next());
138     }
139 tim 1.1 }
140    
141 tim 1.2 // Queue Methods
142    
143     /**
144     * Remove and return the minimal element from this priority queue if
145 brian 1.6 * it contains one or more elements, otherwise return <tt>null</tt>. The term
146 tim 1.2 * <i>minimal</i> is defined according to this priority queue's order.
147     *
148     * @return the minimal element from this priority queue if it contains
149     * one or more elements, otherwise <tt>null</tt>.
150     */
151 tim 1.1 public E poll() {
152 tim 1.2 if (size == 0)
153     return null;
154     return remove(1);
155 tim 1.1 }
156 tim 1.2
157     /**
158     * Return, but do not remove, the minimal element from the priority queue,
159 brian 1.6 * or return <tt>null</tt> if the queue is empty. The term <i>minimal</i> is
160 tim 1.2 * defined according to this priority queue's order. This method returns
161     * the same object reference that would be returned by by the
162 dl 1.5 * <tt>poll</tt> method. The two methods differ in that this method
163 tim 1.2 * does not remove the element from the priority queue.
164     *
165     * @return the minimal element from this priority queue if it contains
166     * one or more elements, otherwise <tt>null</tt>.
167     */
168 tim 1.1 public E peek() {
169 tim 1.2 return queue[1];
170 tim 1.1 }
171    
172 tim 1.2 // Collection Methods
173    
174     /**
175     * Removes a single instance of the specified element from this priority
176     * queue, if it is present. Returns true if this collection contained the
177     * specified element (or equivalently, if this collection changed as a
178     * result of the call).
179     *
180 brian 1.6 * @param element the element to be removed from this collection, if present.
181 tim 1.2 * @return <tt>true</tt> if this collection changed as a result of the
182     * call
183     * @throws ClassCastException if the specified element cannot be compared
184 dl 1.5 * with elements currently in the priority queue according
185 tim 1.2 * to the priority queue's ordering.
186     * @throws NullPointerException if the specified element is null.
187     */
188     public boolean remove(Object element) {
189     if (element == null)
190     throw new NullPointerException();
191    
192     if (comparator == null) {
193     for (int i = 1; i <= size; i++) {
194     if (((Comparable)queue[i]).compareTo(element) == 0) {
195     remove(i);
196     return true;
197     }
198     }
199     } else {
200     for (int i = 1; i <= size; i++) {
201     if (comparator.compare(queue[i], (E) element) == 0) {
202     remove(i);
203     return true;
204     }
205     }
206     }
207 tim 1.1 return false;
208     }
209 tim 1.2
210     /**
211     * Returns an iterator over the elements in this priority queue. The
212 brian 1.6 * elements of the priority queue will be returned by this iterator in the
213     * order specified by the queue, which is to say the order they would be
214     * returned by repeated calls to <tt>poll</tt>.
215 dl 1.5 *
216 tim 1.2 * @return an <tt>Iterator</tt> over the elements in this priority queue.
217     */
218     public Iterator<E> iterator() {
219 dl 1.5 return new Itr();
220 tim 1.2 }
221    
222     private class Itr implements Iterator<E> {
223 dl 1.5 /**
224     * Index (into queue array) of element to be returned by
225 tim 1.2 * subsequent call to next.
226 dl 1.5 */
227     int cursor = 1;
228 tim 1.2
229 dl 1.5 /**
230     * Index of element returned by most recent call to next or
231     * previous. Reset to 0 if this element is deleted by a call
232     * to remove.
233     */
234     int lastRet = 0;
235    
236     /**
237     * The modCount value that the iterator believes that the backing
238     * List should have. If this expectation is violated, the iterator
239     * has detected concurrent modification.
240     */
241     int expectedModCount = modCount;
242    
243     public boolean hasNext() {
244     return cursor <= size;
245     }
246 tim 1.2
247 dl 1.5 public E next() {
248 tim 1.2 checkForComodification();
249     if (cursor > size)
250 dl 1.5 throw new NoSuchElementException();
251 tim 1.2 E result = queue[cursor];
252     lastRet = cursor++;
253     return result;
254 dl 1.5 }
255 tim 1.2
256 dl 1.5 public void remove() {
257     if (lastRet == 0)
258     throw new IllegalStateException();
259 tim 1.2 checkForComodification();
260    
261     PriorityQueue.this.remove(lastRet);
262     if (lastRet < cursor)
263     cursor--;
264     lastRet = 0;
265     expectedModCount = modCount;
266 dl 1.5 }
267 tim 1.2
268 dl 1.5 final void checkForComodification() {
269     if (modCount != expectedModCount)
270     throw new ConcurrentModificationException();
271     }
272 tim 1.2 }
273    
274     /**
275     * Returns the number of elements in this priority queue.
276 dl 1.5 *
277 tim 1.2 * @return the number of elements in this priority queue.
278     */
279 tim 1.1 public int size() {
280 tim 1.2 return size;
281 tim 1.1 }
282 tim 1.2
283     /**
284     * Add the specified element to this priority queue.
285     *
286     * @param element the element to add.
287     * @return true
288     * @throws ClassCastException if the specified element cannot be compared
289 dl 1.5 * with elements currently in the priority queue according
290 tim 1.2 * to the priority queue's ordering.
291     * @throws NullPointerException if the specified element is null.
292     */
293     public boolean offer(E element) {
294     if (element == null)
295     throw new NullPointerException();
296     modCount++;
297    
298     // Grow backing store if necessary
299     if (++size == queue.length) {
300     E[] newQueue = new E[2 * queue.length];
301     System.arraycopy(queue, 0, newQueue, 0, size);
302     queue = newQueue;
303     }
304    
305     queue[size] = element;
306     fixUp(size);
307     return true;
308 tim 1.1 }
309    
310 tim 1.2 /**
311     * Remove all elements from the priority queue.
312     */
313     public void clear() {
314     modCount++;
315    
316     // Null out element references to prevent memory leak
317     for (int i=1; i<=size; i++)
318     queue[i] = null;
319    
320     size = 0;
321     }
322    
323     /**
324     * Removes and returns the ith element from queue. Recall
325     * that queue is one-based, so 1 <= i <= size.
326     *
327     * XXX: Could further special-case i==size, but is it worth it?
328     * XXX: Could special-case i==0, but is it worth it?
329     */
330     private E remove(int i) {
331     assert i <= size;
332     modCount++;
333    
334     E result = queue[i];
335     queue[i] = queue[size];
336     queue[size--] = null; // Drop extra ref to prevent memory leak
337     if (i <= size)
338     fixDown(i);
339     return result;
340 tim 1.1 }
341    
342 tim 1.2 /**
343     * Establishes the heap invariant (described above) assuming the heap
344     * satisfies the invariant except possibly for the leaf-node indexed by k
345     * (which may have a nextExecutionTime less than its parent's).
346     *
347     * This method functions by "promoting" queue[k] up the hierarchy
348     * (by swapping it with its parent) repeatedly until queue[k]
349     * is greater than or equal to its parent.
350     */
351     private void fixUp(int k) {
352     if (comparator == null) {
353     while (k > 1) {
354     int j = k >> 1;
355     if (((Comparable)queue[j]).compareTo(queue[k]) <= 0)
356     break;
357     E tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
358     k = j;
359     }
360     } else {
361     while (k > 1) {
362     int j = k >> 1;
363     if (comparator.compare(queue[j], queue[k]) <= 0)
364     break;
365     E tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
366     k = j;
367     }
368     }
369     }
370    
371     /**
372     * Establishes the heap invariant (described above) in the subtree
373     * rooted at k, which is assumed to satisfy the heap invariant except
374     * possibly for node k itself (which may be greater than its children).
375     *
376     * This method functions by "demoting" queue[k] down the hierarchy
377     * (by swapping it with its smaller child) repeatedly until queue[k]
378     * is less than or equal to its children.
379     */
380     private void fixDown(int k) {
381     int j;
382     if (comparator == null) {
383     while ((j = k << 1) <= size) {
384     if (j<size && ((Comparable)queue[j]).compareTo(queue[j+1]) > 0)
385     j++; // j indexes smallest kid
386     if (((Comparable)queue[k]).compareTo(queue[j]) <= 0)
387     break;
388     E tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
389     k = j;
390     }
391     } else {
392     while ((j = k << 1) <= size) {
393     if (j < size && comparator.compare(queue[j], queue[j+1]) > 0)
394     j++; // j indexes smallest kid
395     if (comparator.compare(queue[k], queue[j]) <= 0)
396     break;
397     E tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
398     k = j;
399     }
400     }
401     }
402    
403     /**
404     * Returns the comparator associated with this priority queue, or
405     * <tt>null</tt> if it uses its elements' natural ordering.
406     *
407     * @return the comparator associated with this priority queue, or
408 dl 1.5 * <tt>null</tt> if it uses its elements' natural ordering.
409 tim 1.2 */
410 dl 1.5 Comparator comparator() {
411 tim 1.2 return comparator;
412     }
413 dl 1.5
414     /**
415     * Save the state of the instance to a stream (that
416     * is, serialize it).
417     *
418     * @serialData The length of the array backing the instance is
419     * emitted (int), followed by all of its elements (each an
420     * <tt>Object</tt>) in the proper order.
421     */
422     private synchronized void writeObject(java.io.ObjectOutputStream s)
423     throws java.io.IOException{
424     // Write out element count, and any hidden stuff
425     s.defaultWriteObject();
426    
427     // Write out array length
428     s.writeInt(queue.length);
429    
430     // Write out all elements in the proper order.
431     for (int i=0; i<size; i++)
432     s.writeObject(queue[i]);
433     }
434    
435     /**
436     * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
437     * deserialize it).
438     */
439     private synchronized void readObject(java.io.ObjectInputStream s)
440     throws java.io.IOException, ClassNotFoundException {
441     // Read in size, and any hidden stuff
442     s.defaultReadObject();
443    
444     // Read in array length and allocate array
445     int arrayLength = s.readInt();
446     queue = new E[arrayLength];
447    
448     // Read in all elements in the proper order.
449     for (int i=0; i<size; i++)
450     queue[i] = (E)s.readObject();
451     }
452    
453 tim 1.1 }