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.10 by tim, Sat Jul 26 13:17:51 2003 UTC vs.
Revision 1.40 by dl, Fri Sep 12 15:38:26 2003 UTC

# Line 1 | Line 1
1 < package java.util;
1 > /*
2 > * %W% %E%
3 > *
4 > * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
5 > * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6 > */
7 >
8 > package java.util;
9  
10   /**
11 < * An unbounded priority queue based on a priority heap.  This queue orders
12 < * elements according to an order specified at construction time, which is
13 < * specified in the same manner as {@link TreeSet} and {@link TreeMap}: elements are ordered
14 < * either according to their <i>natural order</i> (see {@link Comparable}), or
15 < * according to a {@link Comparator}, depending on which constructor is used.
16 < * The {@link #peek}, {@link #poll}, and {@link #remove} methods return the
17 < * minimal element with respect to the specified ordering.  If multiple
18 < * elements are tied for least value, no guarantees are made as to
19 < * which of these elements is returned.
11 > * An unbounded priority {@linkplain Queue queue} based on a priority heap.
12 > * This queue orders elements according to an order specified at construction
13 > * time, which is specified in the same manner as {@link java.util.TreeSet}
14 > * and {@link java.util.TreeMap}: elements are ordered either according to
15 > * their <i>natural order</i> (see {@link Comparable}), or according to a
16 > * {@link java.util.Comparator}, depending on which constructor is used.
17 > *
18 > * <p>The <em>head</em> of this queue is the <em>least</em> element with
19 > * respect to the specified ordering.  If multiple elements are tied for least
20 > * value, the head is one of those elements. A priority queue does not permit
21 > * <tt>null</tt> elements.
22 > *
23 > * <p>The {@link #remove()} and {@link #poll()} methods remove and
24 > * return the head of the queue.
25 > *
26 > * <p>The {@link #element()} and {@link #peek()} methods return, but do
27 > * not delete, the head of the queue.
28 > *
29 > * <p>A priority queue is unbounded, but has a <i>capacity</i>.  The
30 > * capacity is the size of the array used internally to store the
31 > * elements on the queue.  It is always at least as large as the queue
32 > * size.  As elements are added to a priority queue, its capacity
33 > * grows automatically.  The details of the growth policy are not
34 > * specified.
35 > *
36 > * <p>The Iterator provided in method {@link #iterator()} is <em>not</em>
37 > * guaranteed to traverse the elements of the PriorityQueue in any
38 > * particular order. If you need ordered traversal, consider using
39 > * <tt>Arrays.sort(pq.toArray())</tt>.
40   *
41 < * <p>A priority queue has a <i>capacity</i>.  The capacity is the
42 < * size of the array used internally to store the elements on the
43 < * queue.  It is always at least as large as the queue size.  As
44 < * elements are added to a priority queue, its capacity grows
45 < * automatically.  The details of the growth policy are not specified.
41 > * <p> <strong>Note that this implementation is not synchronized.</strong>
42 > * Multiple threads should not access a <tt>PriorityQueue</tt>
43 > * instance concurrently if any of the threads modifies the list
44 > * structurally. Instead, use the thread-safe {@link
45 > * java.util.concurrent.PriorityBlockingQueue} class.
46   *
47 < *<p>Implementation note: this implementation provides O(log(n)) time
48 < *for the insertion methods (<tt>offer</tt>, <tt>poll</tt>,
49 < *<tt>remove()</tt> and <tt>add</tt>) methods; linear time for the
50 < *<tt>remove(Object)</tt> and <tt>contains(Object)</tt> methods; and
51 < *constant time for the retrieval methods (<tt>peek</tt>,
52 < *<tt>element</tt>, and <tt>size</tt>).
47 > *
48 > * <p>Implementation note: this implementation provides O(log(n)) time
49 > * for the insertion methods (<tt>offer</tt>, <tt>poll</tt>,
50 > * <tt>remove()</tt> and <tt>add</tt>) methods; linear time for the
51 > * <tt>remove(Object)</tt> and <tt>contains(Object)</tt> methods; and
52 > * constant time for the retrieval methods (<tt>peek</tt>,
53 > * <tt>element</tt>, and <tt>size</tt>).
54   *
55   * <p>This class is a member of the
56   * <a href="{@docRoot}/../guide/collections/index.html">
57   * Java Collections Framework</a>.
58   * @since 1.5
59 + * @version %I%, %G%
60   * @author Josh Bloch
61   */
62   public class PriorityQueue<E> extends AbstractQueue<E>
63 <                              implements Queue<E>,
64 <                                         java.io.Serializable {
63 >    implements Queue<E>, java.io.Serializable {
64 >
65 >    private static final long serialVersionUID = -7720805057305804111L;
66 >
67      private static final int DEFAULT_INITIAL_CAPACITY = 11;
68  
69      /**
# Line 48 | Line 79 | public class PriorityQueue<E> extends Ab
79       *
80       * queue.length must be >= 2, even if size == 0.
81       */
82 <    private transient E[] queue;
82 >    private transient Object[] queue;
83  
84      /**
85       * The number of elements in the priority queue.
# Line 59 | Line 90 | public class PriorityQueue<E> extends Ab
90       * The comparator, or null if priority queue uses elements'
91       * natural ordering.
92       */
93 <    private final Comparator<E> comparator;
93 >    private final Comparator<? super E> comparator;
94  
95      /**
96       * The number of times this priority queue has been
# Line 68 | Line 99 | public class PriorityQueue<E> extends Ab
99      private transient int modCount = 0;
100  
101      /**
102 <     * Create a new priority queue with the default initial capacity
102 >     * Creates a <tt>PriorityQueue</tt> with the default initial capacity
103       * (11) that orders its elements according to their natural
104 <     * ordering (using <tt>Comparable</tt>.)
104 >     * ordering (using <tt>Comparable</tt>).
105       */
106      public PriorityQueue() {
107 <        this(DEFAULT_INITIAL_CAPACITY);
107 >        this(DEFAULT_INITIAL_CAPACITY, null);
108      }
109  
110      /**
111 <     * Create a new priority queue with the specified initial capacity
111 >     * Creates a <tt>PriorityQueue</tt> with the specified initial capacity
112       * that orders its elements according to their natural ordering
113 <     * (using <tt>Comparable</tt>.)
113 >     * (using <tt>Comparable</tt>).
114       *
115       * @param initialCapacity the initial capacity for this priority queue.
116 +     * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
117 +     * than 1
118       */
119      public PriorityQueue(int initialCapacity) {
120          this(initialCapacity, null);
121      }
122  
123      /**
124 <     * Create a new priority queue with the specified initial capacity (11)
124 >     * Creates a <tt>PriorityQueue</tt> with the specified initial capacity
125       * that orders its elements according to the specified comparator.
126       *
127       * @param initialCapacity the initial capacity for this priority queue.
128       * @param comparator the comparator used to order this priority queue.
129 +     * If <tt>null</tt> then the order depends on the elements' natural
130 +     * ordering.
131 +     * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
132 +     * than 1
133       */
134 <    public PriorityQueue(int initialCapacity, Comparator<E> comparator) {
134 >    public PriorityQueue(int initialCapacity,
135 >                         Comparator<? super E> comparator) {
136          if (initialCapacity < 1)
137 <            initialCapacity = 1;
138 <        queue = (E[]) new Object[initialCapacity + 1];
137 >            throw new IllegalArgumentException();
138 >        this.queue = new Object[initialCapacity + 1];
139          this.comparator = comparator;
140      }
141  
142      /**
143 <     * Create a new priority queue containing the elements in the specified
144 <     * collection.  The priority queue has an initial capacity of 110% of the
107 <     * size of the specified collection. If the specified collection
108 <     * implements the {@link Sorted} interface, the priority queue will be
109 <     * sorted according to the same comparator, or according to its elements'
110 <     * natural order if the collection is sorted according to its elements'
111 <     * natural order.  If the specified collection does not implement
112 <     * <tt>Sorted</tt>, the priority queue is ordered according to
113 <     * its elements' natural order.
114 <     *
115 <     * @param initialElements the collection whose elements are to be placed
116 <     *        into this priority queue.
117 <     * @throws ClassCastException if elements of the specified collection
118 <     *         cannot be compared to one another according to the priority
119 <     *         queue's ordering.
120 <     * @throws NullPointerException if the specified collection or an
121 <     *         element of the specified collection is <tt>null</tt>.
143 >     * Common code to initialize underlying queue array across
144 >     * constructors below.
145       */
146 <    public PriorityQueue(Collection<E> initialElements) {
147 <        int sz = initialElements.size();
146 >    private void initializeArray(Collection<? extends E> c) {
147 >        int sz = c.size();
148          int initialCapacity = (int)Math.min((sz * 110L) / 100,
149                                              Integer.MAX_VALUE - 1);
150          if (initialCapacity < 1)
151              initialCapacity = 1;
129        queue = (E[]) new Object[initialCapacity + 1];
152  
153 +        this.queue = new Object[initialCapacity + 1];
154 +    }
155 +
156 +    /**
157 +     * Initially fill elements of the queue array under the
158 +     * knowledge that it is sorted or is another PQ, in which
159 +     * case we can just place the elements in the order presented.
160 +     */
161 +    private void fillFromSorted(Collection<? extends E> c) {
162 +        for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
163 +            queue[++size] = i.next();
164 +    }
165  
166 <        if (initialElements instanceof Sorted) {
167 <            comparator = ((Sorted)initialElements).comparator();
168 <            for (Iterator<E> i = initialElements.iterator(); i.hasNext(); )
169 <                queue[++size] = i.next();
166 >    /**
167 >     * Initially fill elements of the queue array that is not to our knowledge
168 >     * sorted, so we must rearrange the elements to guarantee the heap
169 >     * invariant.
170 >     */
171 >    private void fillFromUnsorted(Collection<? extends E> c) {
172 >        for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
173 >            queue[++size] = i.next();
174 >        heapify();
175 >    }
176 >
177 >    /**
178 >     * Creates a <tt>PriorityQueue</tt> containing the elements in the
179 >     * specified collection.  The priority queue has an initial
180 >     * capacity of 110% of the size of the specified collection or 1
181 >     * if the collection is empty.  If the specified collection is an
182 >     * instance of a {@link java.util.SortedSet} or is another
183 >     * <tt>PriorityQueue</tt>, the priority queue will be sorted
184 >     * according to the same comparator, or according to its elements'
185 >     * natural order if the collection is sorted according to its
186 >     * elements' natural order.  Otherwise, the priority queue is
187 >     * ordered according to its elements' natural order.
188 >     *
189 >     * @param c the collection whose elements are to be placed
190 >     *        into this priority queue.
191 >     * @throws ClassCastException if elements of the specified collection
192 >     *         cannot be compared to one another according to the priority
193 >     *         queue's ordering.
194 >     * @throws NullPointerException if <tt>c</tt> or any element within it
195 >     * is <tt>null</tt>
196 >     */
197 >    public PriorityQueue(Collection<? extends E> c) {
198 >        initializeArray(c);
199 >        if (c instanceof SortedSet) {
200 >            // @fixme double-cast workaround for compiler
201 >            SortedSet<? extends E> s = (SortedSet<? extends E>) (SortedSet)c;
202 >            comparator = (Comparator<? super E>)s.comparator();
203 >            fillFromSorted(s);
204 >        } else if (c instanceof PriorityQueue) {
205 >            PriorityQueue<? extends E> s = (PriorityQueue<? extends E>) c;
206 >            comparator = (Comparator<? super E>)s.comparator();
207 >            fillFromSorted(s);
208          } else {
209              comparator = null;
210 <            for (Iterator<E> i = initialElements.iterator(); i.hasNext(); )
139 <                add(i.next());
210 >            fillFromUnsorted(c);
211          }
212      }
213  
214 <    // Queue Methods
214 >    /**
215 >     * Creates a <tt>PriorityQueue</tt> containing the elements in the
216 >     * specified collection.  The priority queue has an initial
217 >     * capacity of 110% of the size of the specified collection or 1
218 >     * if the collection is empty.  This priority queue will be sorted
219 >     * according to the same comparator as the given collection, or
220 >     * according to its elements' natural order if the collection is
221 >     * sorted according to its elements' natural order.
222 >     *
223 >     * @param c the collection whose elements are to be placed
224 >     *        into this priority queue.
225 >     * @throws ClassCastException if elements of the specified collection
226 >     *         cannot be compared to one another according to the priority
227 >     *         queue's ordering.
228 >     * @throws NullPointerException if <tt>c</tt> or any element within it
229 >     * is <tt>null</tt>
230 >     */
231 >    public PriorityQueue(PriorityQueue<? extends E> c) {
232 >        initializeArray(c);
233 >        comparator = (Comparator<? super E>)c.comparator();
234 >        fillFromSorted(c);
235 >    }
236  
237      /**
238 <     * Remove and return the minimal element from this priority queue
239 <     * if it contains one or more elements, otherwise return
240 <     * <tt>null</tt>.  The term <i>minimal</i> is defined according to
241 <     * this priority queue's order.
238 >     * Creates a <tt>PriorityQueue</tt> containing the elements in the
239 >     * specified collection.  The priority queue has an initial
240 >     * capacity of 110% of the size of the specified collection or 1
241 >     * if the collection is empty.  This priority queue will be sorted
242 >     * according to the same comparator as the given collection, or
243 >     * according to its elements' natural order if the collection is
244 >     * sorted according to its elements' natural order.
245       *
246 <     * @return the minimal element from this priority queue if it contains
247 <     *         one or more elements, otherwise <tt>null</tt>.
246 >     * @param c the collection whose elements are to be placed
247 >     *        into this priority queue.
248 >     * @throws ClassCastException if elements of the specified collection
249 >     *         cannot be compared to one another according to the priority
250 >     *         queue's ordering.
251 >     * @throws NullPointerException if <tt>c</tt> or any element within it
252 >     * is <tt>null</tt>
253       */
254 <    public E poll() {
255 <        if (size == 0)
256 <            return null;
257 <        return remove(1);
254 >    public PriorityQueue(SortedSet<? extends E> c) {
255 >        initializeArray(c);
256 >        comparator = (Comparator<? super E>)c.comparator();
257 >        fillFromSorted(c);
258 >    }
259 >
260 >    /**
261 >     * Resize array, if necessary, to be able to hold given index
262 >     */
263 >    private void grow(int index) {
264 >        int newlen = queue.length;
265 >        if (index < newlen) // don't need to grow
266 >            return;
267 >        if (index == Integer.MAX_VALUE)
268 >            throw new OutOfMemoryError();
269 >        while (newlen <= index) {
270 >            if (newlen >= Integer.MAX_VALUE / 2)  // avoid overflow
271 >                newlen = Integer.MAX_VALUE;
272 >            else
273 >                newlen <<= 2;
274 >        }
275 >        Object[] newQueue = new Object[newlen];
276 >        System.arraycopy(queue, 0, newQueue, 0, queue.length);
277 >        queue = newQueue;
278      }
279 +            
280  
281      /**
282 <     * Return, but do not remove, the minimal element from the
162 <     * priority queue, or return <tt>null</tt> if the queue is empty.
163 <     * The term <i>minimal</i> is defined according to this priority
164 <     * queue's order.  This method returns the same object reference
165 <     * that would be returned by by the <tt>poll</tt> method.  The two
166 <     * methods differ in that this method does not remove the element
167 <     * from the priority queue.
282 >     * Inserts the specified element to this priority queue.
283       *
284 <     * @return the minimal element from this priority queue if it contains
285 <     *         one or more elements, otherwise <tt>null</tt>.
284 >     * @return <tt>true</tt>
285 >     * @throws ClassCastException if the specified element cannot be compared
286 >     * with elements currently in the priority queue according
287 >     * to the priority queue's ordering.
288 >     * @throws NullPointerException if the specified element is <tt>null</tt>.
289       */
290 +    public boolean offer(E o) {
291 +        if (o == null)
292 +            throw new NullPointerException();
293 +        modCount++;
294 +        ++size;
295 +
296 +        // Grow backing store if necessary
297 +        if (size >= queue.length)
298 +            grow(size);
299 +
300 +        queue[size] = o;
301 +        fixUp(size);
302 +        return true;
303 +    }
304 +
305      public E peek() {
306 <        return queue[1];
306 >        if (size == 0)
307 >            return null;
308 >        return (E) queue[1];
309      }
310  
311 <    // Collection Methods
311 >    // Collection Methods - the first two override to update docs
312  
313      /**
314 <     * Removes a single instance of the specified element from this priority
315 <     * queue, if it is present.  Returns true if this collection contained the
316 <     * specified element (or equivalently, if this collection changed as a
182 <     * result of the call).
314 >     * Adds the specified element to this queue.
315 >     * @return <tt>true</tt> (as per the general contract of
316 >     * <tt>Collection.add</tt>).
317       *
318 <     * @param element the element to be removed from this collection,
185 <     * if present.
186 <     * @return <tt>true</tt> if this collection changed as a result of the
187 <     *         call
318 >     * @throws NullPointerException if the specified element is <tt>null</tt>.
319       * @throws ClassCastException if the specified element cannot be compared
320 <     *            with elements currently in the priority queue according
321 <     *            to the priority queue's ordering.
191 <     * @throws NullPointerException if the specified element is null.
320 >     * with elements currently in the priority queue according
321 >     * to the priority queue's ordering.
322       */
323 <    public boolean remove(Object element) {
324 <        if (element == null)
325 <            throw new NullPointerException();
323 >    public boolean add(E o) {
324 >        return super.add(o);
325 >    }
326 >
327 >  
328 >    /**
329 >     * Adds all of the elements in the specified collection to this queue.
330 >     * The behavior of this operation is undefined if
331 >     * the specified collection is modified while the operation is in
332 >     * progress.  (This implies that the behavior of this call is undefined if
333 >     * the specified collection is this queue, and this queue is nonempty.)
334 >     * <p>
335 >     * This implementation iterates over the specified collection, and adds
336 >     * each object returned by the iterator to this collection, in turn.
337 >     * @param c collection whose elements are to be added to this queue
338 >     * @return <tt>true</tt> if this queue changed as a result of the
339 >     *         call.
340 >     * @throws NullPointerException if <tt>c</tt> or any element in <tt>c</tt>
341 >     * is <tt>null</tt>
342 >     * @throws ClassCastException if any element cannot be compared
343 >     * with elements currently in the priority queue according
344 >     * to the priority queue's ordering.
345 >     */
346 >    public boolean addAll(Collection<? extends E> c) {
347 >        return super.addAll(c);
348 >    }
349 >
350 >    public boolean remove(Object o) {
351 >        if (o == null)
352 >            return false;
353  
354          if (comparator == null) {
355              for (int i = 1; i <= size; i++) {
356 <                if (((Comparable)queue[i]).compareTo(element) == 0) {
357 <                    remove(i);
356 >                if (((Comparable<E>)queue[i]).compareTo((E)o) == 0) {
357 >                    removeAt(i);
358                      return true;
359                  }
360              }
361          } else {
362              for (int i = 1; i <= size; i++) {
363 <                if (comparator.compare(queue[i], (E) element) == 0) {
364 <                    remove(i);
363 >                if (comparator.compare((E)queue[i], (E)o) == 0) {
364 >                    removeAt(i);
365                      return true;
366                  }
367              }
# Line 213 | Line 370 | public class PriorityQueue<E> extends Ab
370      }
371  
372      /**
373 <     * Returns an iterator over the elements in this priority queue.  The
374 <     * elements of the priority queue will be returned by this iterator in the
218 <     * order specified by the queue, which is to say the order they would be
219 <     * returned by repeated calls to <tt>poll</tt>.
373 >     * Returns an iterator over the elements in this queue. The iterator
374 >     * does not return the elements in any particular order.
375       *
376 <     * @return an <tt>Iterator</tt> over the elements in this priority queue.
376 >     * @return an iterator over the elements in this queue.
377       */
378      public Iterator<E> iterator() {
379          return new Itr();
380      }
381  
382      private class Itr implements Iterator<E> {
383 +
384          /**
385           * Index (into queue array) of element to be returned by
386           * subsequent call to next.
# Line 232 | Line 388 | public class PriorityQueue<E> extends Ab
388          private int cursor = 1;
389  
390          /**
391 <         * Index of element returned by most recent call to next or
392 <         * previous.  Reset to 0 if this element is deleted by a call
393 <         * to remove.
391 >         * Index of element returned by most recent call to next,
392 >         * unless that element came from the forgetMeNot list.
393 >         * Reset to 0 if element is deleted by a call to remove.
394           */
395          private int lastRet = 0;
396  
# Line 245 | Line 401 | public class PriorityQueue<E> extends Ab
401           */
402          private int expectedModCount = modCount;
403  
404 +        /**
405 +         * A list of elements that were moved from the unvisited portion of
406 +         * the heap into the visited portion as a result of "unlucky" element
407 +         * removals during the iteration.  (Unlucky element removals are those
408 +         * that require a fixup instead of a fixdown.)  We must visit all of
409 +         * the elements in this list to complete the iteration.  We do this
410 +         * after we've completed the "normal" iteration.
411 +         *
412 +         * We expect that most iterations, even those involving removals,
413 +         * will not use need to store elements in this field.
414 +         */
415 +        private ArrayList<E> forgetMeNot = null;
416 +
417 +        /**
418 +         * Element returned by the most recent call to next iff that
419 +         * element was drawn from the forgetMeNot list.
420 +         */
421 +        private Object lastRetElt = null;
422 +
423          public boolean hasNext() {
424 <            return cursor <= size;
424 >            return cursor <= size || forgetMeNot != null;
425          }
426  
427          public E next() {
428              checkForComodification();
429 <            if (cursor > size)
429 >            E result;
430 >            if (cursor <= size) {
431 >                result = (E) queue[cursor];
432 >                lastRet = cursor++;
433 >            }
434 >            else if (forgetMeNot == null)
435                  throw new NoSuchElementException();
436 <            E result = queue[cursor];
437 <            lastRet = cursor++;
436 >            else {
437 >                int remaining = forgetMeNot.size();
438 >                result = forgetMeNot.remove(remaining - 1);
439 >                if (remaining == 1)
440 >                    forgetMeNot = null;
441 >                lastRet = 0;
442 >                lastRetElt = result;
443 >            }
444              return result;
445          }
446  
447          public void remove() {
262            if (lastRet == 0)
263                throw new IllegalStateException();
448              checkForComodification();
449  
450 <            PriorityQueue.this.remove(lastRet);
451 <            if (lastRet < cursor)
452 <                cursor--;
453 <            lastRet = 0;
450 >            if (lastRet != 0) {
451 >                E moved = PriorityQueue.this.removeAt(lastRet);
452 >                lastRet = 0;
453 >                if (moved == null) {
454 >                    cursor--;
455 >                } else {
456 >                    if (forgetMeNot == null)
457 >                        forgetMeNot = new ArrayList<E>();
458 >                    forgetMeNot.add(moved);
459 >                }
460 >            } else if (lastRetElt != null) {
461 >                PriorityQueue.this.remove(lastRetElt);
462 >                lastRetElt = null;
463 >            } else {
464 >                throw new IllegalStateException();
465 >            }
466 >
467              expectedModCount = modCount;
468          }
469  
# Line 276 | Line 473 | public class PriorityQueue<E> extends Ab
473          }
474      }
475  
279    /**
280     * Returns the number of elements in this priority queue.
281     *
282     * @return the number of elements in this priority queue.
283     */
476      public int size() {
477          return size;
478      }
479  
480      /**
289     * Add the specified element to this priority queue.
290     *
291     * @param element the element to add.
292     * @return true
293     * @throws ClassCastException if the specified element cannot be compared
294     *            with elements currently in the priority queue according
295     *            to the priority queue's ordering.
296     * @throws NullPointerException if the specified element is null.
297     */
298    public boolean offer(E element) {
299        if (element == null)
300            throw new NullPointerException();
301        modCount++;
302        ++size;
303
304        // Grow backing store if necessary
305        while (size >= queue.length) {
306            E[] newQueue = (E[]) new Object[2 * queue.length];
307            System.arraycopy(queue, 0, newQueue, 0, queue.length);
308            queue = newQueue;
309        }
310
311        queue[size] = element;
312        fixUp(size);
313        return true;
314    }
315
316    /**
481       * Remove all elements from the priority queue.
482       */
483      public void clear() {
# Line 326 | Line 490 | public class PriorityQueue<E> extends Ab
490          size = 0;
491      }
492  
493 +    public E poll() {
494 +        if (size == 0)
495 +            return null;
496 +        modCount++;
497 +
498 +        E result = (E) queue[1];
499 +        queue[1] = queue[size];
500 +        queue[size--] = null;  // Drop extra ref to prevent memory leak
501 +        if (size > 1)
502 +            fixDown(1);
503 +
504 +        return result;
505 +    }
506 +
507      /**
508 <     * Removes and returns the ith element from queue.  Recall
509 <     * that queue is one-based, so 1 <= i <= size.
508 >     * Removes and returns the ith element from queue.  (Recall that queue
509 >     * is one-based, so 1 <= i <= size.)
510       *
511 <     * XXX: Could further special-case i==size, but is it worth it?
512 <     * XXX: Could special-case i==0, but is it worth it?
511 >     * Normally this method leaves the elements at positions from 1 up to i-1,
512 >     * inclusive, untouched.  Under these circumstances, it returns null.
513 >     * Occasionally, in order to maintain the heap invariant, it must move
514 >     * the last element of the list to some index in the range [2, i-1],
515 >     * and move the element previously at position (i/2) to position i.
516 >     * Under these circumstances, this method returns the element that was
517 >     * previously at the end of the list and is now at some position between
518 >     * 2 and i-1 inclusive.
519       */
520 <    private E remove(int i) {
521 <        assert i <= size;
520 >    private E removeAt(int i) {
521 >        assert i > 0 && i <= size;
522          modCount++;
523  
524 <        E result = queue[i];
525 <        queue[i] = queue[size];
524 >        E moved = (E) queue[size];
525 >        queue[i] = moved;
526          queue[size--] = null;  // Drop extra ref to prevent memory leak
527 <        if (i <= size)
527 >        if (i <= size) {
528              fixDown(i);
529 <        return result;
529 >            if (queue[i] == moved) {
530 >                fixUp(i);
531 >                if (queue[i] != moved)
532 >                    return moved;
533 >            }
534 >        }
535 >        return null;
536      }
537  
538      /**
# Line 358 | Line 548 | public class PriorityQueue<E> extends Ab
548          if (comparator == null) {
549              while (k > 1) {
550                  int j = k >> 1;
551 <                if (((Comparable)queue[j]).compareTo(queue[k]) <= 0)
551 >                if (((Comparable<E>)queue[j]).compareTo((E)queue[k]) <= 0)
552                      break;
553 <                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
553 >                Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
554                  k = j;
555              }
556          } else {
557              while (k > 1) {
558 <                int j = k >> 1;
559 <                if (comparator.compare(queue[j], queue[k]) <= 0)
558 >                int j = k >>> 1;
559 >                if (comparator.compare((E)queue[j], (E)queue[k]) <= 0)
560                      break;
561 <                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
561 >                Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
562                  k = j;
563              }
564          }
# Line 386 | Line 576 | public class PriorityQueue<E> extends Ab
576      private void fixDown(int k) {
577          int j;
578          if (comparator == null) {
579 <            while ((j = k << 1) <= size) {
580 <                if (j<size && ((Comparable)queue[j]).compareTo(queue[j+1]) > 0)
579 >            while ((j = k << 1) <= size && (j > 0)) {
580 >                if (j<size &&
581 >                    ((Comparable<E>)queue[j]).compareTo((E)queue[j+1]) > 0)
582                      j++; // j indexes smallest kid
583 <                if (((Comparable)queue[k]).compareTo(queue[j]) <= 0)
583 >
584 >                if (((Comparable<E>)queue[k]).compareTo((E)queue[j]) <= 0)
585                      break;
586 <                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
586 >                Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
587                  k = j;
588              }
589          } else {
590 <            while ((j = k << 1) <= size) {
591 <                if (j < size && comparator.compare(queue[j], queue[j+1]) > 0)
590 >            while ((j = k << 1) <= size && (j > 0)) {
591 >                if (j<size &&
592 >                    comparator.compare((E)queue[j], (E)queue[j+1]) > 0)
593                      j++; // j indexes smallest kid
594 <                if (comparator.compare(queue[k], queue[j]) <= 0)
594 >                if (comparator.compare((E)queue[k], (E)queue[j]) <= 0)
595                      break;
596 <                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
596 >                Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
597                  k = j;
598              }
599          }
600      }
601  
602      /**
603 <     * Returns the comparator associated with this priority queue, or
604 <     * <tt>null</tt> if it uses its elements' natural ordering.
603 >     * Establishes the heap invariant (described above) in the entire tree,
604 >     * assuming nothing about the order of the elements prior to the call.
605 >     */
606 >    private void heapify() {
607 >        for (int i = size/2; i >= 1; i--)
608 >            fixDown(i);
609 >    }
610 >
611 >    /**
612 >     * Returns the comparator used to order this collection, or <tt>null</tt>
613 >     * if this collection is sorted according to its elements natural ordering
614 >     * (using <tt>Comparable</tt>).
615       *
616 <     * @return the comparator associated with this priority queue, or
617 <     *         <tt>null</tt> if it uses its elements' natural ordering.
616 >     * @return the comparator used to order this collection, or <tt>null</tt>
617 >     * if this collection is sorted according to its elements natural ordering.
618       */
619 <    public Comparator comparator() {
619 >    public Comparator<? super E> comparator() {
620          return comparator;
621      }
622  
# Line 426 | Line 629 | public class PriorityQueue<E> extends Ab
629       * <tt>Object</tt>) in the proper order.
630       * @param s the stream
631       */
632 <    private synchronized void writeObject(java.io.ObjectOutputStream s)
632 >    private void writeObject(java.io.ObjectOutputStream s)
633          throws java.io.IOException{
634          // Write out element count, and any hidden stuff
635          s.defaultWriteObject();
# Line 435 | Line 638 | public class PriorityQueue<E> extends Ab
638          s.writeInt(queue.length);
639  
640          // Write out all elements in the proper order.
641 <        for (int i=0; i<size; i++)
641 >        for (int i=1; i<=size; i++)
642              s.writeObject(queue[i]);
643      }
644  
# Line 444 | Line 647 | public class PriorityQueue<E> extends Ab
647       * deserialize it).
648       * @param s the stream
649       */
650 <    private synchronized void readObject(java.io.ObjectInputStream s)
650 >    private void readObject(java.io.ObjectInputStream s)
651          throws java.io.IOException, ClassNotFoundException {
652          // Read in size, and any hidden stuff
653          s.defaultReadObject();
654  
655          // Read in array length and allocate array
656          int arrayLength = s.readInt();
657 <        queue = (E[]) new Object[arrayLength];
657 >        queue = new Object[arrayLength];
658  
659          // Read in all elements in the proper order.
660 <        for (int i=0; i<size; i++)
661 <            queue[i] = (E)s.readObject();
660 >        for (int i=1; i<=size; i++)
661 >            queue[i] = (E) s.readObject();
662      }
663  
664   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines