ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/PriorityQueue.java
(Generate patch)

Comparing jsr166/src/main/java/util/PriorityQueue.java (file contents):
Revision 1.6 by brian, Mon Jun 23 02:26:15 2003 UTC vs.
Revision 1.20 by dholmes, Tue Aug 5 06:18:17 2003 UTC

# Line 3 | Line 3
3   /**
4   * An unbounded priority queue based on a priority heap.  This queue orders
5   * 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
6 > * specified in the same manner as {@link java.util.TreeSet} and
7 > * {@link java.util.TreeMap}: elements are ordered
8   * either according to their <i>natural order</i> (see {@link Comparable}), or
9 < * according to a {@link Comparator}, depending on which constructor is used.
10 < * The {@link #peek}, {@link #poll}, and {@link #remove} methods return the
11 < * minimal element with respect to the specified ordering.  If multiple
12 < * elements are tied for least value, no guarantees are made as to
13 < * which of these elements is returned.
9 > * according to a {@link java.util.Comparator}, depending on which
10 > * constructor is used.
11 > * <p>The <em>head</em> of this queue is the <em>least</em> element with
12 > * respect to the specified ordering.
13 > * If multiple elements are tied for least value, the
14 > * head is one of those elements. A priority queue does not permit
15 > * <tt>null</tt> elements.
16   *
17 < * <p>A priority queue has a <i>capacity</i>.  The capacity is the size of
18 < * 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 < * its capacity grows automatically.  The details of the growth policy are not
18 < * specified.
17 > * <p>The {@link #remove()} and {@link #poll()} methods remove and
18 > * return the head of the queue.
19   *
20 < *<p>Implementation note: this implementation provides O(log(n)) time for
21 < * the insertion methods (<tt>offer</tt>, <tt>poll</tt>, <tt>remove()</tt> and <tt>add</tt>)
22 < * methods; linear time for the <tt>remove(Object)</tt> and
23 < * <tt>contains(Object)</tt> methods; and constant time for the retrieval methods (<tt>peek</tt>,
20 > * <p>The {@link #element()} and {@link #peek()} methods return, but do
21 > * not delete, the head of the queue.
22 > *
23 > * <p>A priority queue has a <i>capacity</i>.  The capacity is the
24 > * size of the array used internally to store the elements on the
25 > * queue.
26 > * It is always at least as large as the queue size.  As
27 > * elements are added to a priority queue, its capacity grows
28 > * automatically.  The details of the growth policy are not specified.
29 > *
30 > * <p>Implementation note: this implementation provides O(log(n)) time
31 > * for the insertion methods (<tt>offer</tt>, <tt>poll</tt>,
32 > * <tt>remove()</tt> and <tt>add</tt>) methods; linear time for the
33 > * <tt>remove(Object)</tt> and <tt>contains(Object)</tt> methods; and
34 > * constant time for the retrieval methods (<tt>peek</tt>,
35   * <tt>element</tt>, and <tt>size</tt>).
36   *
37   * <p>This class is a member of the
38   * <a href="{@docRoot}/../guide/collections/index.html">
39   * Java Collections Framework</a>.
40 + * @since 1.5
41 + * @author Josh Bloch
42   */
43   public class PriorityQueue<E> extends AbstractQueue<E>
44 <                              implements Queue<E>
45 < {
44 >    implements Sorted, Queue<E>, java.io.Serializable {
45 >
46      private static final int DEFAULT_INITIAL_CAPACITY = 11;
47  
48      /**
# Line 45 | Line 58 | public class PriorityQueue<E> extends Ab
58       *
59       * queue.length must be >= 2, even if size == 0.
60       */
61 <    private transient E[] queue;
61 >    private transient Object[] queue;
62  
63      /**
64       * The number of elements in the priority queue.
# Line 56 | Line 69 | public class PriorityQueue<E> extends Ab
69       * The comparator, or null if priority queue uses elements'
70       * natural ordering.
71       */
72 <    private final Comparator<E> comparator;
72 >    private final Comparator<? super E> comparator;
73  
74      /**
75       * The number of times this priority queue has been
# Line 65 | Line 78 | public class PriorityQueue<E> extends Ab
78      private transient int modCount = 0;
79  
80      /**
81 <     * Create a new priority queue with the default initial capacity (11)
82 <     * that orders its elements according to their natural ordering (using <tt>Comparable</tt>.)
81 >     * Create a <tt>PriorityQueue</tt> with the default initial capacity
82 >     * (11) that orders its elements according to their natural
83 >     * ordering (using <tt>Comparable</tt>.)
84       */
85      public PriorityQueue() {
86 <        this(DEFAULT_INITIAL_CAPACITY);
86 >        this(DEFAULT_INITIAL_CAPACITY, null);
87      }
88  
89      /**
90 <     * Create a new priority queue with the specified initial capacity
91 <     * that orders its elements according to their natural ordering (using <tt>Comparable</tt>.)
90 >     * Create a <tt>PriorityQueue</tt> with the specified initial capacity
91 >     * that orders its elements according to their natural ordering
92 >     * (using <tt>Comparable</tt>.)
93       *
94       * @param initialCapacity the initial capacity for this priority queue.
95       */
# Line 83 | Line 98 | public class PriorityQueue<E> extends Ab
98      }
99  
100      /**
101 <     * Create a new priority queue with the specified initial capacity (11)
101 >     * Create a <tt>PriorityQueue</tt> with the specified initial capacity
102       * that orders its elements according to the specified comparator.
103       *
104       * @param initialCapacity the initial capacity for this priority queue.
105       * @param comparator the comparator used to order this priority queue.
106 +     * If <tt>null</tt> then the order depends on the elements' natural
107 +     * ordering.
108 +     * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
109 +     * than 1
110       */
111 <    public PriorityQueue(int initialCapacity, Comparator<E> comparator) {
111 >    public PriorityQueue(int initialCapacity, Comparator<? super E> comparator) {
112          if (initialCapacity < 1)
113 <            initialCapacity = 1;
114 <        queue = new E[initialCapacity + 1];
113 >            throw new IllegalArgumentException();
114 >        this.queue = new Object[initialCapacity + 1];
115          this.comparator = comparator;
116      }
117  
118      /**
119 <     * Create a new priority queue containing the elements in the specified
119 >     * Create a <tt>PriorityQueue</tt> containing the elements in the specified
120       * collection.  The priority queue has an initial capacity of 110% of the
121 <     * size of the specified collection. If the specified collection
121 >     * size of the specified collection or 1 if the collection is empty.
122 >     * If the specified collection
123       * implements the {@link Sorted} interface, the priority queue will be
124       * sorted according to the same comparator, or according to its elements'
125       * natural order if the collection is sorted according to its elements'
# Line 107 | Line 127 | public class PriorityQueue<E> extends Ab
127       * <tt>Sorted</tt>, the priority queue is ordered according to
128       * its elements' natural order.
129       *
130 <     * @param initialElements the collection whose elements are to be placed
130 >     * @param c the collection whose elements are to be placed
131       *        into this priority queue.
132       * @throws ClassCastException if elements of the specified collection
133       *         cannot be compared to one another according to the priority
134       *         queue's ordering.
135 <     * @throws NullPointerException if the specified collection or an
136 <     *         element of the specified collection is <tt>null</tt>.
135 >     * @throws NullPointerException if <tt>c</tt> or any element within it
136 >     * is <tt>null</tt>
137       */
138 <    public PriorityQueue(Collection<E> initialElements) {
139 <        int sz = initialElements.size();
138 >    public PriorityQueue(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;
124        queue = new E[initialCapacity + 1];
144  
145 <        /* Commented out to compile with generics compiler
145 >        this.queue = new Object[initialCapacity + 1];
146  
147 <        if (initialElements instanceof Sorted) {
148 <            comparator = ((Sorted)initialElements).comparator();
130 <            for (Iterator<E> i = initialElements.iterator(); i.hasNext(); )
131 <                queue[++size] = i.next();
147 >        if (c instanceof Sorted) {
148 >            comparator = (Comparator<? super E>)((Sorted)c).comparator();
149          } else {
133        */
134        {
150              comparator = null;
136            for (Iterator<E> i = initialElements.iterator(); i.hasNext(); )
137                add(i.next());
151          }
152 +
153 +        for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
154 +            add(i.next());
155      }
156  
157      // Queue Methods
158  
159      /**
160 <     * Remove and return the minimal element from this priority queue if
145 <     * it contains one or more elements, otherwise return <tt>null</tt>.  The term
146 <     * <i>minimal</i> is defined according to this priority queue's order.
160 >     * Add the specified element to this priority queue.
161       *
162 <     * @return the minimal element from this priority queue if it contains
163 <     *         one or more elements, otherwise <tt>null</tt>.
162 >     * @return <tt>true</tt>
163 >     * @throws ClassCastException if the specified element cannot be compared
164 >     * with elements currently in the priority queue according
165 >     * to the priority queue's ordering.
166 >     * @throws NullPointerException if the specified element is <tt>null</tt>.
167       */
168 +    public boolean offer(E o) {
169 +        if (o == null)
170 +            throw new NullPointerException();
171 +        modCount++;
172 +        ++size;
173 +
174 +        // Grow backing store if necessary
175 +        while (size >= queue.length) {
176 +            Object[] newQueue = new Object[2 * queue.length];
177 +            System.arraycopy(queue, 0, newQueue, 0, queue.length);
178 +            queue = newQueue;
179 +        }
180 +
181 +        queue[size] = o;
182 +        fixUp(size);
183 +        return true;
184 +    }
185 +
186      public E poll() {
187          if (size == 0)
188              return null;
189 <        return remove(1);
189 >        return (E) remove(1);
190      }
191  
157    /**
158     * Return, but do not remove, the minimal element from the priority queue,
159     * or return <tt>null</tt> if the queue is empty.  The term <i>minimal</i> is
160     * defined according to this priority queue's order.  This method returns
161     * the same object reference that would be returned by by the
162     * <tt>poll</tt> method.  The two methods differ in that this method
163     * 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     */
192      public E peek() {
193 <        return queue[1];
193 >        return (E) queue[1];
194      }
195  
196      // Collection Methods
197  
198 +    // these first two override just to get the throws docs
199 +
200      /**
201 <     * 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 <     * @param element the element to be removed from this collection, if present.
181 <     * @return <tt>true</tt> if this collection changed as a result of the
182 <     *         call
201 >     * @throws NullPointerException if the specified element is <tt>null</tt>.
202       * @throws ClassCastException if the specified element cannot be compared
203 <     *            with elements currently in the priority queue according
204 <     *            to the priority queue's ordering.
186 <     * @throws NullPointerException if the specified element is null.
203 >     * with elements currently in the priority queue according
204 >     * to the priority queue's ordering.
205       */
206 <    public boolean remove(Object element) {
207 <        if (element == null)
208 <            throw new NullPointerException();
206 >    public boolean add(E o) {
207 >        return super.add(o);
208 >    }
209 >
210 >    /**
211 >     * @throws ClassCastException if any element cannot be compared
212 >     * with elements currently in the priority queue according
213 >     * to the priority queue's ordering.
214 >     * @throws NullPointerException if <tt>c</tt> or any element in <tt>c</tt>
215 >     * is <tt>null</tt>
216 >     */
217 >    public boolean addAll(Collection<? extends E> c) {
218 >        return super.addAll(c);
219 >    }
220 >
221 >    public boolean remove(Object o) {
222 >        if (o == null)
223 >            return false;
224  
225          if (comparator == null) {
226              for (int i = 1; i <= size; i++) {
227 <                if (((Comparable)queue[i]).compareTo(element) == 0) {
227 >                if (((Comparable<E>)queue[i]).compareTo((E)o) == 0) {
228                      remove(i);
229                      return true;
230                  }
231              }
232          } else {
233              for (int i = 1; i <= size; i++) {
234 <                if (comparator.compare(queue[i], (E) element) == 0) {
234 >                if (comparator.compare((E)queue[i], (E)o) == 0) {
235                      remove(i);
236                      return true;
237                  }
# Line 207 | Line 240 | public class PriorityQueue<E> extends Ab
240          return false;
241      }
242  
210    /**
211     * Returns an iterator over the elements in this priority queue.  The
212     * 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     *
216     * @return an <tt>Iterator</tt> over the elements in this priority queue.
217     */
243      public Iterator<E> iterator() {
244 <        return new Itr();
244 >        return new Itr();
245      }
246  
247      private class Itr implements Iterator<E> {
248 <        /**
249 <         * Index (into queue array) of element to be returned by
248 >        /**
249 >         * Index (into queue array) of element to be returned by
250           * subsequent call to next.
251 <         */
252 <        int cursor = 1;
251 >         */
252 >        private int cursor = 1;
253  
254 <        /**
255 <         * Index of element returned by most recent call to next or
256 <         * previous.  Reset to 0 if this element is deleted by a call
257 <         * to remove.
258 <         */
259 <        int lastRet = 0;
260 <
261 <        /**
262 <         * The modCount value that the iterator believes that the backing
263 <         * List should have.  If this expectation is violated, the iterator
264 <         * has detected concurrent modification.
265 <         */
266 <        int expectedModCount = modCount;
267 <
268 <        public boolean hasNext() {
269 <            return cursor <= size;
270 <        }
254 >        /**
255 >         * Index of element returned by most recent call to next or
256 >         * previous.  Reset to 0 if this element is deleted by a call
257 >         * to remove.
258 >         */
259 >        private int lastRet = 0;
260 >
261 >        /**
262 >         * The modCount value that the iterator believes that the backing
263 >         * List should have.  If this expectation is violated, the iterator
264 >         * has detected concurrent modification.
265 >         */
266 >        private int expectedModCount = modCount;
267 >
268 >        public boolean hasNext() {
269 >            return cursor <= size;
270 >        }
271  
272 <        public E next() {
272 >        public E next() {
273              checkForComodification();
274              if (cursor > size)
275 <                throw new NoSuchElementException();
276 <            E result = queue[cursor];
275 >                throw new NoSuchElementException();
276 >            E result = (E) queue[cursor];
277              lastRet = cursor++;
278              return result;
279 <        }
279 >        }
280  
281 <        public void remove() {
282 <            if (lastRet == 0)
283 <                throw new IllegalStateException();
281 >        public void remove() {
282 >            if (lastRet == 0)
283 >                throw new IllegalStateException();
284              checkForComodification();
285  
286              PriorityQueue.this.remove(lastRet);
# Line 263 | Line 288 | public class PriorityQueue<E> extends Ab
288                  cursor--;
289              lastRet = 0;
290              expectedModCount = modCount;
291 <        }
291 >        }
292  
293 <        final void checkForComodification() {
294 <            if (modCount != expectedModCount)
295 <                throw new ConcurrentModificationException();
296 <        }
293 >        final void checkForComodification() {
294 >            if (modCount != expectedModCount)
295 >                throw new ConcurrentModificationException();
296 >        }
297      }
298  
299      /**
300       * Returns the number of elements in this priority queue.
301 <     *
301 >     *
302       * @return the number of elements in this priority queue.
303       */
304      public int size() {
# Line 281 | Line 306 | public class PriorityQueue<E> extends Ab
306      }
307  
308      /**
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     *            with elements currently in the priority queue according
290     *            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    }
309
310    /**
309       * Remove all elements from the priority queue.
310       */
311      public void clear() {
# Line 331 | Line 329 | public class PriorityQueue<E> extends Ab
329          assert i <= size;
330          modCount++;
331  
332 <        E result = queue[i];
332 >        E result = (E) queue[i];
333          queue[i] = queue[size];
334          queue[size--] = null;  // Drop extra ref to prevent memory leak
335          if (i <= size)
# Line 352 | Line 350 | public class PriorityQueue<E> extends Ab
350          if (comparator == null) {
351              while (k > 1) {
352                  int j = k >> 1;
353 <                if (((Comparable)queue[j]).compareTo(queue[k]) <= 0)
353 >                if (((Comparable<E>)queue[j]).compareTo((E)queue[k]) <= 0)
354                      break;
355 <                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
355 >                Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
356                  k = j;
357              }
358          } else {
359              while (k > 1) {
360                  int j = k >> 1;
361 <                if (comparator.compare(queue[j], queue[k]) <= 0)
361 >                if (comparator.compare((E)queue[j], (E)queue[k]) <= 0)
362                      break;
363 <                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
363 >                Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
364                  k = j;
365              }
366          }
# Line 381 | Line 379 | public class PriorityQueue<E> extends Ab
379          int j;
380          if (comparator == null) {
381              while ((j = k << 1) <= size) {
382 <                if (j<size && ((Comparable)queue[j]).compareTo(queue[j+1]) > 0)
382 >                if (j<size && ((Comparable<E>)queue[j]).compareTo((E)queue[j+1]) > 0)
383                      j++; // j indexes smallest kid
384 <                if (((Comparable)queue[k]).compareTo(queue[j]) <= 0)
384 >                if (((Comparable<E>)queue[k]).compareTo((E)queue[j]) <= 0)
385                      break;
386 <                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
386 >                Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
387                  k = j;
388              }
389          } else {
390              while ((j = k << 1) <= size) {
391 <                if (j < size && comparator.compare(queue[j], queue[j+1]) > 0)
391 >                if (j < size && comparator.compare((E)queue[j], (E)queue[j+1]) > 0)
392                      j++; // j indexes smallest kid
393 <                if (comparator.compare(queue[k], queue[j]) <= 0)
393 >                if (comparator.compare((E)queue[k], (E)queue[j]) <= 0)
394                      break;
395 <                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
395 >                Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
396                  k = j;
397              }
398          }
399      }
400  
401 <    /**
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 <     *         <tt>null</tt> if it uses its elements' natural ordering.
409 <     */
410 <    Comparator comparator() {
401 >    public Comparator<? super E> comparator() {
402          return comparator;
403      }
404  
# Line 418 | Line 409 | public class PriorityQueue<E> extends Ab
409       * @serialData The length of the array backing the instance is
410       * emitted (int), followed by all of its elements (each an
411       * <tt>Object</tt>) in the proper order.
412 +     * @param s the stream
413       */
414      private synchronized void writeObject(java.io.ObjectOutputStream s)
415          throws java.io.IOException{
416 <        // Write out element count, and any hidden stuff
417 <        s.defaultWriteObject();
416 >        // Write out element count, and any hidden stuff
417 >        s.defaultWriteObject();
418  
419          // Write out array length
420          s.writeInt(queue.length);
421  
422 <        // Write out all elements in the proper order.
423 <        for (int i=0; i<size; i++)
422 >        // Write out all elements in the proper order.
423 >        for (int i=0; i<size; i++)
424              s.writeObject(queue[i]);
425      }
426  
427      /**
428       * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
429       * deserialize it).
430 +     * @param s the stream
431       */
432      private synchronized void readObject(java.io.ObjectInputStream s)
433          throws java.io.IOException, ClassNotFoundException {
434 <        // Read in size, and any hidden stuff
435 <        s.defaultReadObject();
434 >        // Read in size, and any hidden stuff
435 >        s.defaultReadObject();
436  
437          // Read in array length and allocate array
438          int arrayLength = s.readInt();
439 <        queue = new E[arrayLength];
439 >        queue = new Object[arrayLength];
440  
441 <        // Read in all elements in the proper order.
442 <        for (int i=0; i<size; i++)
443 <            queue[i] = (E)s.readObject();
441 >        // Read in all elements in the proper order.
442 >        for (int i=0; i<size; i++)
443 >            queue[i] = s.readObject();
444      }
445  
446   }
447 +

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines