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.15 by dholmes, Thu Jul 31 07:18:02 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 TreeSet} and {@link TreeMap}:
7 > * 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.
10 > * The <em>head</em> of this queue is the least element with respect to the
11 > * specified ordering. If multiple elements are tied for least value, the
12 > * head is one of those elements. A priority queue does not permit
13 > * <tt>null</tt> elements.
14   *
15 < * <p>A priority queue has a <i>capacity</i>.  The capacity is the size of
16 < * 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.
15 > * <p>The {@link #remove()} and {@link #poll()} methods remove and
16 > * return the head of the queue.
17   *
18 < *<p>Implementation note: this implementation provides O(log(n)) time for
19 < * the insertion methods (<tt>offer</tt>, <tt>poll</tt>, <tt>remove()</tt> and <tt>add</tt>)
20 < * methods; linear time for the <tt>remove(Object)</tt> and
21 < * <tt>contains(Object)</tt> methods; and constant time for the retrieval methods (<tt>peek</tt>,
18 > * <p>The {@link #element()} and {@link #peek()} methods return, but do
19 > * not delete, the head of the queue.
20 > *
21 > * <p>A priority queue has a <i>capacity</i>.  The capacity is the
22 > * size of the array used internally to store the elements on the
23 > * queue.  It is always at least as large as the queue size.  As
24 > * elements are added to a priority queue, its capacity grows
25 > * automatically.  The details of the growth policy are not specified.
26 > *
27 > * <p>Implementation note: this implementation provides O(log(n)) time
28 > * for the insertion methods (<tt>offer</tt>, <tt>poll</tt>,
29 > * <tt>remove()</tt> and <tt>add</tt>) methods; linear time for the
30 > * <tt>remove(Object)</tt> and <tt>contains(Object)</tt> methods; and
31 > * constant time for the retrieval methods (<tt>peek</tt>,
32   * <tt>element</tt>, and <tt>size</tt>).
33   *
34   * <p>This class is a member of the
35   * <a href="{@docRoot}/../guide/collections/index.html">
36   * Java Collections Framework</a>.
37 + * @since 1.5
38 + * @author Josh Bloch
39   */
40   public class PriorityQueue<E> extends AbstractQueue<E>
41 <                              implements Queue<E>
42 < {
41 >    implements Queue<E>, java.io.Serializable {
42 >
43      private static final int DEFAULT_INITIAL_CAPACITY = 11;
44  
45      /**
# Line 65 | Line 75 | public class PriorityQueue<E> extends Ab
75      private transient int modCount = 0;
76  
77      /**
78 <     * Create a new priority queue with the default initial capacity (11)
79 <     * that orders its elements according to their natural ordering (using <tt>Comparable</tt>.)
78 >     * Create a <tt>PriorityQueue</tt> with the default initial capacity
79 >     * (11) that orders its elements according to their natural
80 >     * ordering (using <tt>Comparable</tt>.)
81       */
82      public PriorityQueue() {
83 <        this(DEFAULT_INITIAL_CAPACITY);
83 >        this(DEFAULT_INITIAL_CAPACITY, null);
84      }
85  
86      /**
87 <     * Create a new priority queue with the specified initial capacity
88 <     * that orders its elements according to their natural ordering (using <tt>Comparable</tt>.)
87 >     * Create a <tt>PriorityQueue</tt> with the specified initial capacity
88 >     * that orders its elements according to their natural ordering
89 >     * (using <tt>Comparable</tt>.)
90       *
91       * @param initialCapacity the initial capacity for this priority queue.
92       */
# Line 83 | Line 95 | public class PriorityQueue<E> extends Ab
95      }
96  
97      /**
98 <     * Create a new priority queue with the specified initial capacity (11)
98 >     * Create a <tt>PriorityQueue</tt> with the specified initial capacity
99       * that orders its elements according to the specified comparator.
100       *
101       * @param initialCapacity the initial capacity for this priority queue.
102       * @param comparator the comparator used to order this priority queue.
103 +     * If <tt>null</tt> then the order depends on the elements' natural
104 +     * ordering.
105 +     * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
106 +     * than 1
107       */
108      public PriorityQueue(int initialCapacity, Comparator<E> comparator) {
109          if (initialCapacity < 1)
110 <            initialCapacity = 1;
111 <        queue = new E[initialCapacity + 1];
110 >            throw new IllegalArgumentException();
111 >        queue = (E[]) new Object[initialCapacity + 1];
112          this.comparator = comparator;
113      }
114  
115      /**
116 <     * Create a new priority queue containing the elements in the specified
116 >     * Create a <tt>PriorityQueue</tt> containing the elements in the specified
117       * collection.  The priority queue has an initial capacity of 110% of the
118 <     * size of the specified collection. If the specified collection
118 >     * size of the specified collection; or 1 if the collection is empty.
119 >     * If the specified collection
120       * implements the {@link Sorted} interface, the priority queue will be
121       * sorted according to the same comparator, or according to its elements'
122       * natural order if the collection is sorted according to its elements'
# Line 107 | Line 124 | public class PriorityQueue<E> extends Ab
124       * <tt>Sorted</tt>, the priority queue is ordered according to
125       * its elements' natural order.
126       *
127 <     * @param initialElements the collection whose elements are to be placed
127 >     * @param c the collection whose elements are to be placed
128       *        into this priority queue.
129       * @throws ClassCastException if elements of the specified collection
130       *         cannot be compared to one another according to the priority
131       *         queue's ordering.
132 <     * @throws NullPointerException if the specified collection or an
133 <     *         element of the specified collection is <tt>null</tt>.
132 >     * @throws NullPointerException if <tt>c</tt> or any element within it
133 >     * is <tt>null</tt>
134       */
135 <    public PriorityQueue(Collection<E> initialElements) {
136 <        int sz = initialElements.size();
135 >    public PriorityQueue(Collection<E> c) {
136 >        int sz = c.size();
137          int initialCapacity = (int)Math.min((sz * 110L) / 100,
138                                              Integer.MAX_VALUE - 1);
139          if (initialCapacity < 1)
140              initialCapacity = 1;
124        queue = new E[initialCapacity + 1];
141  
142 <        /* Commented out to compile with generics compiler
142 >        queue = (E[]) new Object[initialCapacity + 1];
143  
144 <        if (initialElements instanceof Sorted) {
145 <            comparator = ((Sorted)initialElements).comparator();
146 <            for (Iterator<E> i = initialElements.iterator(); i.hasNext(); )
144 >        if (c instanceof Sorted) {
145 >            // FIXME: this code assumes too much
146 >            comparator = ((Sorted)c).comparator();
147 >            for (Iterator<E> i = c.iterator(); i.hasNext(); )
148                  queue[++size] = i.next();
149          } else {
133        */
134        {
150              comparator = null;
151 <            for (Iterator<E> i = initialElements.iterator(); i.hasNext(); )
151 >            for (Iterator<E> i = c.iterator(); i.hasNext(); )
152                  add(i.next());
153          }
154      }
# Line 141 | Line 156 | public class PriorityQueue<E> extends Ab
156      // Queue Methods
157  
158      /**
159 <     * 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.
159 >     * Add the specified element to this priority queue.
160       *
161 <     * @return the minimal element from this priority queue if it contains
162 <     *         one or more elements, otherwise <tt>null</tt>.
161 >     * @param element the element to add.
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 null.
167       */
168 +    public boolean offer(E element) {
169 +        if (element == null)
170 +            throw new NullPointerException();
171 +        modCount++;
172 +        ++size;
173 +
174 +        // Grow backing store if necessary
175 +        while (size >= queue.length) {
176 +            E[] newQueue = (E[]) new Object[2 * queue.length];
177 +            System.arraycopy(queue, 0, newQueue, 0, queue.length);
178 +            queue = newQueue;
179 +        }
180 +
181 +        queue[size] = element;
182 +        fixUp(size);
183 +        return true;
184 +    }
185 +
186      public E poll() {
187          if (size == 0)
188              return null;
189          return 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];
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 element) {
207 >        return super.add(element);
208 >    }
209 >
210 >    /**
211 >     * @throws NullPointerException if any element is <tt>null</tt>.
212 >     * @throws ClassCastException if any element cannot be compared
213 >     * with elements currently in the priority queue according
214 >     * to the priority queue's ordering.
215 >     */
216 >    public boolean addAll(Collection<? extends E> c) {
217 >        return super.addAll(c);
218 >    }
219 >
220 >    public boolean remove(Object o) {
221 >        if (o == null)
222 >            return false;
223  
224          if (comparator == null) {
225              for (int i = 1; i <= size; i++) {
226 <                if (((Comparable)queue[i]).compareTo(element) == 0) {
226 >                if (((Comparable)queue[i]).compareTo(o) == 0) {
227                      remove(i);
228                      return true;
229                  }
230              }
231          } else {
232              for (int i = 1; i <= size; i++) {
233 <                if (comparator.compare(queue[i], (E) element) == 0) {
233 >                if (comparator.compare(queue[i], (E)o) == 0) {
234                      remove(i);
235                      return true;
236                  }
# Line 207 | Line 239 | public class PriorityQueue<E> extends Ab
239          return false;
240      }
241  
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     */
242      public Iterator<E> iterator() {
243 <        return new Itr();
243 >        return new Itr();
244      }
245  
246      private class Itr implements Iterator<E> {
247 <        /**
248 <         * Index (into queue array) of element to be returned by
247 >        /**
248 >         * Index (into queue array) of element to be returned by
249           * subsequent call to next.
250 <         */
251 <        int cursor = 1;
250 >         */
251 >        private int cursor = 1;
252  
253 <        /**
254 <         * Index of element returned by most recent call to next or
255 <         * previous.  Reset to 0 if this element is deleted by a call
256 <         * to remove.
257 <         */
258 <        int lastRet = 0;
259 <
260 <        /**
261 <         * The modCount value that the iterator believes that the backing
262 <         * List should have.  If this expectation is violated, the iterator
263 <         * has detected concurrent modification.
264 <         */
265 <        int expectedModCount = modCount;
266 <
267 <        public boolean hasNext() {
268 <            return cursor <= size;
269 <        }
253 >        /**
254 >         * Index of element returned by most recent call to next or
255 >         * previous.  Reset to 0 if this element is deleted by a call
256 >         * to remove.
257 >         */
258 >        private int lastRet = 0;
259 >
260 >        /**
261 >         * The modCount value that the iterator believes that the backing
262 >         * List should have.  If this expectation is violated, the iterator
263 >         * has detected concurrent modification.
264 >         */
265 >        private int expectedModCount = modCount;
266 >
267 >        public boolean hasNext() {
268 >            return cursor <= size;
269 >        }
270  
271 <        public E next() {
271 >        public E next() {
272              checkForComodification();
273              if (cursor > size)
274 <                throw new NoSuchElementException();
274 >                throw new NoSuchElementException();
275              E result = queue[cursor];
276              lastRet = cursor++;
277              return result;
278 <        }
278 >        }
279  
280 <        public void remove() {
281 <            if (lastRet == 0)
282 <                throw new IllegalStateException();
280 >        public void remove() {
281 >            if (lastRet == 0)
282 >                throw new IllegalStateException();
283              checkForComodification();
284  
285              PriorityQueue.this.remove(lastRet);
# Line 263 | Line 287 | public class PriorityQueue<E> extends Ab
287                  cursor--;
288              lastRet = 0;
289              expectedModCount = modCount;
290 <        }
290 >        }
291  
292 <        final void checkForComodification() {
293 <            if (modCount != expectedModCount)
294 <                throw new ConcurrentModificationException();
295 <        }
292 >        final void checkForComodification() {
293 >            if (modCount != expectedModCount)
294 >                throw new ConcurrentModificationException();
295 >        }
296      }
297  
298      /**
299       * Returns the number of elements in this priority queue.
300 <     *
300 >     *
301       * @return the number of elements in this priority queue.
302       */
303      public int size() {
# Line 281 | Line 305 | public class PriorityQueue<E> extends Ab
305      }
306  
307      /**
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    /**
308       * Remove all elements from the priority queue.
309       */
310      public void clear() {
# Line 400 | Line 397 | public class PriorityQueue<E> extends Ab
397          }
398      }
399  
400 <    /**
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() {
400 >    public Comparator comparator() {
401          return comparator;
402      }
403  
# Line 418 | Line 408 | public class PriorityQueue<E> extends Ab
408       * @serialData The length of the array backing the instance is
409       * emitted (int), followed by all of its elements (each an
410       * <tt>Object</tt>) in the proper order.
411 +     * @param s the stream
412       */
413      private synchronized void writeObject(java.io.ObjectOutputStream s)
414          throws java.io.IOException{
415 <        // Write out element count, and any hidden stuff
416 <        s.defaultWriteObject();
415 >        // Write out element count, and any hidden stuff
416 >        s.defaultWriteObject();
417  
418          // Write out array length
419          s.writeInt(queue.length);
420  
421 <        // Write out all elements in the proper order.
422 <        for (int i=0; i<size; i++)
421 >        // Write out all elements in the proper order.
422 >        for (int i=0; i<size; i++)
423              s.writeObject(queue[i]);
424      }
425  
426      /**
427       * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
428       * deserialize it).
429 +     * @param s the stream
430       */
431      private synchronized void readObject(java.io.ObjectInputStream s)
432          throws java.io.IOException, ClassNotFoundException {
433 <        // Read in size, and any hidden stuff
434 <        s.defaultReadObject();
433 >        // Read in size, and any hidden stuff
434 >        s.defaultReadObject();
435  
436          // Read in array length and allocate array
437          int arrayLength = s.readInt();
438 <        queue = new E[arrayLength];
438 >        queue = (E[]) new Object[arrayLength];
439  
440 <        // Read in all elements in the proper order.
441 <        for (int i=0; i<size; i++)
440 >        // Read in all elements in the proper order.
441 >        for (int i=0; i<size; i++)
442              queue[i] = (E)s.readObject();
443      }
444  
445   }
446 +

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines