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.34 by dholmes, Wed Aug 27 01:33:50 2003 UTC vs.
Revision 1.54 by jsr166, Thu Nov 24 03:44:57 2005 UTC

# Line 1 | Line 1
1 < package java.util;
1 > /*
2 > * @(#)PriorityQueue.java       1.8 05/08/27
3 > *
4 > * Copyright 2005 Sun Microsystems, Inc. All rights reserved.
5 > * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6 > */
7 >
8 > package java.util;
9 > import java.util.*; // for javadoc (till 6280605 is fixed)
10  
11   /**
12 < * An unbounded priority {@linkplain Queue queue} based on a priority heap.  
13 < * This queue orders
14 < * elements according to an order specified at construction time, which is
15 < * specified in the same manner as {@link java.util.TreeSet} and
16 < * {@link java.util.TreeMap}: elements are ordered
17 < * either according to their <i>natural order</i> (see {@link Comparable}), or
18 < * according to a {@link java.util.Comparator}, depending on which
19 < * constructor is used.
12 < * <p>The <em>head</em> of this queue is the <em>least</em> element with
13 < * respect to the specified ordering.
14 < * If multiple elements are tied for least value, the
15 < * head is one of those elements. A priority queue does not permit
16 < * <tt>null</tt> elements.
12 > * An unbounded priority {@linkplain Queue queue} based on a priority
13 > * heap.  The elements of the priority queue are ordered according to
14 > * their {@linkplain Comparable natural ordering}, or by a {@link
15 > * Comparator} provided at queue construction time, depending on which
16 > * constructor is used.  A priority queue does not permit
17 > * <tt>null</tt> elements.  A priority queue relying on natural
18 > * ordering also does not permit insertion of non-comparable objects
19 > * (doing so may result in <tt>ClassCastException</tt>).
20   *
21 < * <p>The {@link #remove()} and {@link #poll()} methods remove and
22 < * return the head of the queue.
21 > * <p>The <em>head</em> of this queue is the <em>least</em> element
22 > * with respect to the specified ordering.  If multiple elements are
23 > * tied for least value, the head is one of those elements -- ties are
24 > * broken arbitrarily.  The queue retrieval operations <tt>poll</tt>,
25 > * <tt>remove</tt>, <tt>peek</tt>, and <tt>element</tt> access the
26 > * element at the head of the queue.
27   *
28 < * <p>The {@link #element()} and {@link #peek()} methods return, but do
29 < * not delete, the head of the queue.
28 > * <p>A priority queue is unbounded, but has an internal
29 > * <i>capacity</i> governing the size of an array used to store the
30 > * elements on the queue.  It is always at least as large as the queue
31 > * size.  As elements are added to a priority queue, its capacity
32 > * grows automatically.  The details of the growth policy are not
33 > * specified.
34   *
35 < * <p>A priority queue has a <i>capacity</i>.  The capacity is the
36 < * size of the array used internally to store the elements on the
37 < * queue.
38 < * It is always at least as large as the queue size.  As
39 < * elements are added to a priority queue, its capacity grows
40 < * automatically.  The details of the growth policy are not specified.
30 < *
31 < * <p>The Iterator provided in method {@link #iterator()} is <em>not</em>
32 < * guaranteed to traverse the elements of the PriorityQueue in any
33 < * particular order. If you need ordered traversal, consider using
34 < * <tt>Arrays.sort(pq.toArray())</tt>.
35 > * <p>This class and its iterator implement all of the
36 > * <em>optional</em> methods of the {@link Collection} and {@link
37 > * Iterator} interfaces.  The Iterator provided in method {@link
38 > * #iterator()} is <em>not</em> guaranteed to traverse the elements of
39 > * the priority queue in any particular order. If you need ordered
40 > * traversal, consider using <tt>Arrays.sort(pq.toArray())</tt>.
41   *
42   * <p> <strong>Note that this implementation is not synchronized.</strong>
43   * Multiple threads should not access a <tt>PriorityQueue</tt>
# Line 39 | Line 45
45   * structurally. Instead, use the thread-safe {@link
46   * java.util.concurrent.PriorityBlockingQueue} class.
47   *
42 *
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
# Line 51 | Line 56
56   * <a href="{@docRoot}/../guide/collections/index.html">
57   * Java Collections Framework</a>.
58   * @since 1.5
59 + * @version 1.8, 08/27/05
60   * @author Josh Bloch
61 + * @param <E> the type of elements held in this collection
62   */
63   public class PriorityQueue<E> extends AbstractQueue<E>
64 <    implements Queue<E>, java.io.Serializable {
64 >    implements java.io.Serializable {
65  
66      private static final long serialVersionUID = -7720805057305804111L;
67  
# Line 93 | Line 100 | public class PriorityQueue<E> extends Ab
100      private transient int modCount = 0;
101  
102      /**
103 <     * Creates a <tt>PriorityQueue</tt> with the default initial capacity
104 <     * (11) that orders its elements according to their natural
105 <     * ordering (using <tt>Comparable</tt>).
103 >     * Creates a <tt>PriorityQueue</tt> with the default initial
104 >     * capacity (11) that orders its elements according to their
105 >     * {@linkplain Comparable natural ordering}.
106       */
107      public PriorityQueue() {
108          this(DEFAULT_INITIAL_CAPACITY, null);
109      }
110  
111      /**
112 <     * Creates a <tt>PriorityQueue</tt> with the specified initial capacity
113 <     * that orders its elements according to their natural ordering
114 <     * (using <tt>Comparable</tt>).
112 >     * Creates a <tt>PriorityQueue</tt> with the specified initial
113 >     * capacity that orders its elements according to their
114 >     * {@linkplain Comparable natural ordering}.
115       *
116 <     * @param initialCapacity the initial capacity for this priority queue.
116 >     * @param initialCapacity the initial capacity for this priority queue
117       * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
118       * than 1
119       */
# Line 118 | Line 125 | public class PriorityQueue<E> extends Ab
125       * Creates a <tt>PriorityQueue</tt> with the specified initial capacity
126       * that orders its elements according to the specified comparator.
127       *
128 <     * @param initialCapacity the initial capacity for this priority queue.
129 <     * @param comparator the comparator used to order this priority queue.
130 <     * If <tt>null</tt> then the order depends on the elements' natural
131 <     * ordering.
132 <     * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
133 <     * than 1
128 >     * @param  initialCapacity the initial capacity for this priority queue
129 >     * @param  comparator the comparator that will be used to order
130 >     *         this priority queue.  If <tt>null</tt>, the <i>natural
131 >     *         ordering</i> of the elements will be used.
132 >     * @throws IllegalArgumentException if <tt>initialCapacity</tt> is
133 >     *         less than 1
134       */
135 <    public PriorityQueue(int initialCapacity,
135 >    public PriorityQueue(int initialCapacity,
136                           Comparator<? super E> comparator) {
137          if (initialCapacity < 1)
138              throw new IllegalArgumentException();
# Line 148 | Line 155 | public class PriorityQueue<E> extends Ab
155      }
156  
157      /**
158 <     * Initially fill elements of the queue array under the
158 >     * Initially fill elements of the queue array under the
159       * knowledge that it is sorted or is another PQ, in which
160 <     * case we can just place the elements without fixups.
160 >     * case we can just place the elements in the order presented.
161       */
162      private void fillFromSorted(Collection<? extends E> c) {
163 <        for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
164 <            queue[++size] = i.next();
163 >        for (Iterator<? extends E> i = c.iterator(); i.hasNext(); ) {
164 >            int k = ++size;
165 >            if (k >= queue.length)
166 >                grow(k);
167 >            queue[k] = i.next();
168 >        }
169      }
170  
160
171      /**
172 <     * Initially fill elements of the queue array that is
173 <     * not to our knowledge sorted, so we must add them
174 <     * one by one.
172 >     * Initially fill elements of the queue array that is not to our knowledge
173 >     * sorted, so we must rearrange the elements to guarantee the heap
174 >     * invariant.
175       */
176      private void fillFromUnsorted(Collection<? extends E> c) {
177 <        for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
178 <            add(i.next());
177 >        for (Iterator<? extends E> i = c.iterator(); i.hasNext(); ) {
178 >            int k = ++size;
179 >            if (k >= queue.length)
180 >                grow(k);
181 >            queue[k] = i.next();
182 >        }
183 >        heapify();
184      }
185  
186      /**
# Line 174 | Line 189 | public class PriorityQueue<E> extends Ab
189       * capacity of 110% of the size of the specified collection or 1
190       * if the collection is empty.  If the specified collection is an
191       * instance of a {@link java.util.SortedSet} or is another
192 <     * <tt>PriorityQueue</tt>, the priority queue will be sorted
193 <     * according to the same comparator, or according to its elements'
194 <     * natural order if the collection is sorted according to its
180 <     * elements' natural order.  Otherwise, the priority queue is
181 <     * ordered according to its elements' natural order.
192 >     * <tt>PriorityQueue</tt>, the priority queue will be ordered
193 >     * according to the same ordering.  Otherwise, this priority queue
194 >     * will be ordered according to the natural ordering of its elements.
195       *
196 <     * @param c the collection whose elements are to be placed
197 <     *        into this priority queue.
196 >     * @param  c the collection whose elements are to be placed
197 >     *         into this priority queue
198       * @throws ClassCastException if elements of the specified collection
199       *         cannot be compared to one another according to the priority
200 <     *         queue's ordering.
201 <     * @throws NullPointerException if <tt>c</tt> or any element within it
202 <     * is <tt>null</tt>
200 >     *         queue's ordering
201 >     * @throws NullPointerException if the specified collection or any
202 >     *         of its elements are null
203       */
204      public PriorityQueue(Collection<? extends E> c) {
205          initializeArray(c);
206          if (c instanceof SortedSet) {
207 <            // @fixme double-cast workaround for compiler
195 <            SortedSet<? extends E> s = (SortedSet<? extends E>) (SortedSet)c;
207 >            SortedSet<? extends E> s = (SortedSet<? extends E>)c;
208              comparator = (Comparator<? super E>)s.comparator();
209              fillFromSorted(s);
210          } else if (c instanceof PriorityQueue) {
# Line 207 | Line 219 | public class PriorityQueue<E> extends Ab
219  
220      /**
221       * Creates a <tt>PriorityQueue</tt> containing the elements in the
222 <     * specified collection.  The priority queue has an initial
223 <     * capacity of 110% of the size of the specified collection or 1
224 <     * if the collection is empty.  This priority queue will be sorted
225 <     * according to the same comparator as the given collection, or
226 <     * according to its elements' natural order if the collection is
227 <     * sorted according to its elements' natural order.
228 <     *
229 <     * @param c the collection whose elements are to be placed
230 <     *        into this priority queue.
231 <     * @throws ClassCastException if elements of the specified collection
232 <     *         cannot be compared to one another according to the priority
233 <     *         queue's ordering.
234 <     * @throws NullPointerException if <tt>c</tt> or any element within it
223 <     * is <tt>null</tt>
222 >     * specified priority queue.  The priority queue has an initial
223 >     * capacity of 110% of the size of the specified priority queue or
224 >     * 1 if the priority queue is empty.  This priority queue will be
225 >     * ordered according to the same ordering as the given priority
226 >     * queue.
227 >     *
228 >     * @param  c the priority queue whose elements are to be placed
229 >     *         into this priority queue
230 >     * @throws ClassCastException if elements of <tt>c</tt> cannot be
231 >     *         compared to one another according to <tt>c</tt>'s
232 >     *         ordering
233 >     * @throws NullPointerException if the specified priority queue or any
234 >     *         of its elements are null
235       */
236      public PriorityQueue(PriorityQueue<? extends E> c) {
237          initializeArray(c);
# Line 230 | Line 241 | public class PriorityQueue<E> extends Ab
241  
242      /**
243       * Creates a <tt>PriorityQueue</tt> containing the elements in the
244 <     * specified collection.  The priority queue has an initial
245 <     * capacity of 110% of the size of the specified collection or 1
246 <     * if the collection is empty.  This priority queue will be sorted
247 <     * according to the same comparator as the given collection, or
248 <     * according to its elements' natural order if the collection is
249 <     * sorted according to its elements' natural order.
250 <     *
251 <     * @param c the collection whose elements are to be placed
252 <     *        into this priority queue.
253 <     * @throws ClassCastException if elements of the specified collection
254 <     *         cannot be compared to one another according to the priority
255 <     *         queue's ordering.
245 <     * @throws NullPointerException if <tt>c</tt> or any element within it
246 <     * is <tt>null</tt>
244 >     * specified sorted set.  The priority queue has an initial
245 >     * capacity of 110% of the size of the specified sorted set or 1
246 >     * if the sorted set is empty.  This priority queue will be ordered
247 >     * according to the same ordering as the given sorted set.
248 >     *
249 >     * @param  c the sorted set whose elements are to be placed
250 >     *         into this priority queue.
251 >     * @throws ClassCastException if elements of the specified sorted
252 >     *         set cannot be compared to one another according to the
253 >     *         sorted set's ordering
254 >     * @throws NullPointerException if the specified sorted set or any
255 >     *         of its elements are null
256       */
257      public PriorityQueue(SortedSet<? extends E> c) {
258          initializeArray(c);
# Line 252 | Line 261 | public class PriorityQueue<E> extends Ab
261      }
262  
263      /**
264 <     * Resize array, if necessary, to be able to hold given index
264 >     * Resize array, if necessary, to be able to hold given index.
265       */
266      private void grow(int index) {
267          int newlen = queue.length;
# Line 264 | Line 273 | public class PriorityQueue<E> extends Ab
273              if (newlen >= Integer.MAX_VALUE / 2)  // avoid overflow
274                  newlen = Integer.MAX_VALUE;
275              else
276 <                newlen <<= 2;
276 >                newlen <<= 1;
277          }
278 <        Object[] newQueue = new Object[newlen];
270 <        System.arraycopy(queue, 0, newQueue, 0, queue.length);
271 <        queue = newQueue;
278 >        queue = Arrays.copyOf(queue, newlen);
279      }
273            
274    // Queue Methods
275
280  
281 +    /**
282 +     * Inserts the specified element into this priority queue.
283 +     *
284 +     * @return <tt>true</tt> (as specified by {@link Collection#add})
285 +     * @throws ClassCastException if the specified element cannot be
286 +     *         compared with elements currently in this priority queue
287 +     *         according to the priority queue's ordering
288 +     * @throws NullPointerException if the specified element is null
289 +     */
290 +    public boolean add(E e) {
291 +        return offer(e);
292 +    }
293  
294      /**
295 <     * Add the specified element to this priority queue.
295 >     * Inserts the specified element into this priority queue.
296       *
297 <     * @return <tt>true</tt>
298 <     * @throws ClassCastException if the specified element cannot be compared
299 <     * with elements currently in the priority queue according
300 <     * to the priority queue's ordering.
301 <     * @throws NullPointerException if the specified element is <tt>null</tt>.
297 >     * @return <tt>true</tt> (as specified by {@link Queue#offer})
298 >     * @throws ClassCastException if the specified element cannot be
299 >     *         compared with elements currently in this priority queue
300 >     *         according to the priority queue's ordering
301 >     * @throws NullPointerException if the specified element is null
302       */
303 <    public boolean offer(E o) {
304 <        if (o == null)
303 >    public boolean offer(E e) {
304 >        if (e == null)
305              throw new NullPointerException();
306          modCount++;
307          ++size;
308  
309          // Grow backing store if necessary
310 <        if (size >= queue.length)
310 >        if (size >= queue.length)
311              grow(size);
312  
313 <        queue[size] = o;
313 >        queue[size] = e;
314          fixUp(size);
315          return true;
316      }
317  
318 <    public E poll() {
318 >    public E peek() {
319          if (size == 0)
320              return null;
305        return (E) remove(1);
306    }
307
308    public E peek() {
321          return (E) queue[1];
322      }
323  
324 <    // Collection Methods - the first two override to update docs
324 >    private int indexOf(Object o) {
325 >        if (o == null)
326 >            return -1;
327 >        for (int i = 1; i <= size; i++)
328 >            if (o.equals(queue[i]))
329 >                return i;
330 >        return -1;
331 >    }
332  
333      /**
334 <     * Adds the specified element to this queue.
335 <     * @return <tt>true</tt> (as per the general contract of
336 <     * <tt>Collection.add</tt>).
337 <     *
338 <     * @throws NullPointerException {@inheritDoc}
339 <     * @throws ClassCastException if the specified element cannot be compared
340 <     * with elements currently in the priority queue according
341 <     * to the priority queue's ordering.
342 <     */
343 <    public boolean add(E o) {
344 <        return super.add(o);
345 <    }
346 <
347 <  
348 <    /**
349 <     * Adds all of the elements in the specified collection to this queue.
350 <     * The behavior of this operation is undefined if
332 <     * the specified collection is modified while the operation is in
333 <     * progress.  (This implies that the behavior of this call is undefined if
334 <     * the specified collection is this queue, and this queue is nonempty.)
335 <     * <p>
336 <     * This implementation iterates over the specified collection, and adds
337 <     * each object returned by the iterator to this collection, in turn.
338 <     * @throws NullPointerException {@inheritDoc}
339 <     * @throws ClassCastException if any element cannot be compared
340 <     * with elements currently in the priority queue according
341 <     * to the priority queue's ordering.
342 <     */
343 <    public boolean addAll(Collection<? extends E> c) {
344 <        return super.addAll(c);
334 >     * Removes a single instance of the specified element from this queue,
335 >     * if it is present.  More formally, removes an element <tt>e</tt> such
336 >     * that <tt>o.equals(e)</tt>, if this queue contains one or more such
337 >     * elements.  Returns true if this queue contained the specified element
338 >     * (or equivalently, if this queue changed as a result of the call).
339 >     *
340 >     * @param o element to be removed from this queue, if present
341 >     * @return <tt>true</tt> if this queue changed as a result of the call
342 >     */
343 >    public boolean remove(Object o) {
344 >        int i = indexOf(o);
345 >        if (i == -1)
346 >            return false;
347 >        else {
348 >            removeAt(i);
349 >            return true;
350 >        }
351      }
352  
353 +    /**
354 +     * Returns <tt>true</tt> if this queue contains the specified element.
355 +     * More formally, returns <tt>true</tt> if and only if this queue contains
356 +     * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
357 +     *
358 +     * @param o object to be checked for containment in this queue
359 +     * @return <tt>true</tt> if this queue contains the specified element
360 +     */
361 +    public boolean contains(Object o) {
362 +        return indexOf(o) != -1;
363 +    }
364  
365 < /**
366 <     * Removes a single instance of the specified element from this
367 <     * queue, if it is present.  More formally,
368 <     * removes an element <tt>e</tt> such that <tt>(o==null ? e==null :
369 <     * o.equals(e))</tt>, if the queue contains one or more such
370 <     * elements.  Returns <tt>true</tt> if the queue contained the
371 <     * specified element (or equivalently, if the queue changed as a
355 <     * result of the call).
356 <     *
357 <     * <p>This implementation iterates over the queue looking for the
358 <     * specified element.  If it finds the element, it removes the element
359 <     * from the queue using the iterator's remove method.<p>
365 >    /**
366 >     * Returns an array containing all of the elements in this queue,
367 >     * The elements are in no particular order.
368 >     *
369 >     * <p>The returned array will be "safe" in that no references to it are
370 >     * maintained by this list.  (In other words, this method must allocate
371 >     * a new array).  The caller is thus free to modify the returned array.
372       *
373 +     * @return an array containing all of the elements in this queue.
374       */
375 <    public boolean remove(Object o) {
376 <        if (o == null)
377 <            return false;
375 >    public Object[] toArray() {
376 >        return Arrays.copyOfRange(queue, 1, size+1);
377 >    }
378  
379 <        if (comparator == null) {
380 <            for (int i = 1; i <= size; i++) {
381 <                if (((Comparable<E>)queue[i]).compareTo((E)o) == 0) {
382 <                    remove(i);
383 <                    return true;
384 <                }
385 <            }
386 <        } else {
387 <            for (int i = 1; i <= size; i++) {
388 <                if (comparator.compare((E)queue[i], (E)o) == 0) {
389 <                    remove(i);
390 <                    return true;
391 <                }
392 <            }
393 <        }
394 <        return false;
379 >    /**
380 >     * Returns an array containing all of the elements in this queue.
381 >     * The elements are in no particular order.  The runtime type of
382 >     * the returned array is that of the specified array.  If the queue
383 >     * fits in the specified array, it is returned therein.
384 >     * Otherwise, a new array is allocated with the runtime type of
385 >     * the specified array and the size of this queue.
386 >     *
387 >     * <p>If the queue fits in the specified array with room to spare
388 >     * (i.e., the array has more elements than the queue), the element in
389 >     * the array immediately following the end of the collection is set to
390 >     * <tt>null</tt>.  (This is useful in determining the length of the
391 >     * queue <i>only</i> if the caller knows that the queue does not contain
392 >     * any null elements.)
393 >     *
394 >     * @param a the array into which the elements of the queue are to
395 >     *          be stored, if it is big enough; otherwise, a new array of the
396 >     *          same runtime type is allocated for this purpose.
397 >     * @return an array containing the elements of the queue
398 >     * @throws ArrayStoreException if the runtime type of the specified array
399 >     *         is not a supertype of the runtime type of every element in
400 >     *         this queue
401 >     * @throws NullPointerException if the specified array is null
402 >     */
403 >    public <T> T[] toArray(T[] a) {
404 >        if (a.length < size)
405 >            // Make a new array of a's runtime type, but my contents:
406 >            return (T[]) Arrays.copyOfRange(queue, 1, size+1, a.getClass());
407 >        System.arraycopy(queue, 1, a, 0, size);
408 >        if (a.length > size)
409 >            a[size] = null;
410 >        return a;
411      }
412  
413      /**
414       * Returns an iterator over the elements in this queue. The iterator
415       * does not return the elements in any particular order.
416       *
417 <     * @return an iterator over the elements in this queue.
417 >     * @return an iterator over the elements in this queue
418       */
419      public Iterator<E> iterator() {
420          return new Itr();
421      }
422  
423      private class Itr implements Iterator<E> {
424 +
425          /**
426           * Index (into queue array) of element to be returned by
427           * subsequent call to next.
# Line 399 | Line 429 | public class PriorityQueue<E> extends Ab
429          private int cursor = 1;
430  
431          /**
432 <         * Index of element returned by most recent call to next or
433 <         * previous.  Reset to 0 if this element is deleted by a call
434 <         * to remove.
432 >         * Index of element returned by most recent call to next,
433 >         * unless that element came from the forgetMeNot list.
434 >         * Reset to 0 if element is deleted by a call to remove.
435           */
436          private int lastRet = 0;
437  
# Line 412 | Line 442 | public class PriorityQueue<E> extends Ab
442           */
443          private int expectedModCount = modCount;
444  
445 +        /**
446 +         * A list of elements that were moved from the unvisited portion of
447 +         * the heap into the visited portion as a result of "unlucky" element
448 +         * removals during the iteration.  (Unlucky element removals are those
449 +         * that require a fixup instead of a fixdown.)  We must visit all of
450 +         * the elements in this list to complete the iteration.  We do this
451 +         * after we've completed the "normal" iteration.
452 +         *
453 +         * We expect that most iterations, even those involving removals,
454 +         * will not use need to store elements in this field.
455 +         */
456 +        private ArrayList<E> forgetMeNot = null;
457 +
458 +        /**
459 +         * Element returned by the most recent call to next iff that
460 +         * element was drawn from the forgetMeNot list.
461 +         */
462 +        private Object lastRetElt = null;
463 +
464          public boolean hasNext() {
465 <            return cursor <= size;
465 >            return cursor <= size || forgetMeNot != null;
466          }
467  
468          public E next() {
469              checkForComodification();
470 <            if (cursor > size)
470 >            E result;
471 >            if (cursor <= size) {
472 >                result = (E) queue[cursor];
473 >                lastRet = cursor++;
474 >            }
475 >            else if (forgetMeNot == null)
476                  throw new NoSuchElementException();
477 <            E result = (E) queue[cursor];
478 <            lastRet = cursor++;
477 >            else {
478 >                int remaining = forgetMeNot.size();
479 >                result = forgetMeNot.remove(remaining - 1);
480 >                if (remaining == 1)
481 >                    forgetMeNot = null;
482 >                lastRet = 0;
483 >                lastRetElt = result;
484 >            }
485              return result;
486          }
487  
488          public void remove() {
429            if (lastRet == 0)
430                throw new IllegalStateException();
489              checkForComodification();
490  
491 <            PriorityQueue.this.remove(lastRet);
492 <            cursor--;
493 <            lastRet = 0;
491 >            if (lastRet != 0) {
492 >                E moved = PriorityQueue.this.removeAt(lastRet);
493 >                lastRet = 0;
494 >                if (moved == null) {
495 >                    cursor--;
496 >                } else {
497 >                    if (forgetMeNot == null)
498 >                        forgetMeNot = new ArrayList<E>();
499 >                    forgetMeNot.add(moved);
500 >                }
501 >            } else if (lastRetElt != null) {
502 >                PriorityQueue.this.remove(lastRetElt);
503 >                lastRetElt = null;
504 >            } else {
505 >                throw new IllegalStateException();
506 >            }
507 >
508              expectedModCount = modCount;
509          }
510  
# Line 447 | Line 519 | public class PriorityQueue<E> extends Ab
519      }
520  
521      /**
522 <     * Remove all elements from the priority queue.
522 >     * Removes all of the elements from this priority queue.
523 >     * The queue will be empty after this call returns.
524       */
525      public void clear() {
526          modCount++;
# Line 459 | Line 532 | public class PriorityQueue<E> extends Ab
532          size = 0;
533      }
534  
535 +    public E poll() {
536 +        if (size == 0)
537 +            return null;
538 +        modCount++;
539 +
540 +        E result = (E) queue[1];
541 +        queue[1] = queue[size];
542 +        queue[size--] = null;  // Drop extra ref to prevent memory leak
543 +        if (size > 1)
544 +            fixDown(1);
545 +
546 +        return result;
547 +    }
548 +
549      /**
550 <     * Removes and returns the ith element from queue.  Recall
551 <     * that queue is one-based, so 1 <= i <= size.
550 >     * Removes and returns the ith element from queue.  (Recall that queue
551 >     * is one-based, so 1 <= i <= size.)
552       *
553 +     * Normally this method leaves the elements at positions from 1 up to i-1,
554 +     * inclusive, untouched.  Under these circumstances, it returns null.
555 +     * Occasionally, in order to maintain the heap invariant, it must move
556 +     * the last element of the list to some index in the range [2, i-1],
557 +     * and move the element previously at position (i/2) to position i.
558 +     * Under these circumstances, this method returns the element that was
559 +     * previously at the end of the list and is now at some position between
560 +     * 2 and i-1 inclusive.
561       */
562 <    private E remove(int i) {
563 <        assert i <= size;
562 >    private E removeAt(int i) {
563 >        assert i > 0 && i <= size;
564          modCount++;
565  
566 <        E result = (E) queue[i];
567 <        queue[i] = queue[size];
566 >        E moved = (E) queue[size];
567 >        queue[i] = moved;
568          queue[size--] = null;  // Drop extra ref to prevent memory leak
569 <        if (i <= size)
569 >        if (i <= size) {
570              fixDown(i);
571 <        return result;
571 >            if (queue[i] == moved) {
572 >                fixUp(i);
573 >                if (queue[i] != moved)
574 >                    return moved;
575 >            }
576 >        }
577 >        return null;
578      }
579  
580      /**
# Line 489 | Line 590 | public class PriorityQueue<E> extends Ab
590          if (comparator == null) {
591              while (k > 1) {
592                  int j = k >> 1;
593 <                if (((Comparable<E>)queue[j]).compareTo((E)queue[k]) <= 0)
593 >                if (((Comparable<? super E>)queue[j]).compareTo((E)queue[k]) <= 0)
594                      break;
595                  Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
596                  k = j;
597              }
598          } else {
599              while (k > 1) {
600 <                int j = k >> 1;
600 >                int j = k >>> 1;
601                  if (comparator.compare((E)queue[j], (E)queue[k]) <= 0)
602                      break;
603                  Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
# Line 518 | Line 619 | public class PriorityQueue<E> extends Ab
619          int j;
620          if (comparator == null) {
621              while ((j = k << 1) <= size && (j > 0)) {
622 <                if (j<size && ((Comparable<E>)queue[j]).compareTo((E)queue[j+1]) > 0)
622 >                if (j<size &&
623 >                    ((Comparable<? super E>)queue[j]).compareTo((E)queue[j+1]) > 0)
624                      j++; // j indexes smallest kid
625 <                if (((Comparable<E>)queue[k]).compareTo((E)queue[j]) <= 0)
625 >
626 >                if (((Comparable<? super E>)queue[k]).compareTo((E)queue[j]) <= 0)
627                      break;
628                  Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
629                  k = j;
630              }
631          } else {
632              while ((j = k << 1) <= size && (j > 0)) {
633 <                if (j < size && comparator.compare((E)queue[j], (E)queue[j+1]) > 0)
633 >                if (j<size &&
634 >                    comparator.compare((E)queue[j], (E)queue[j+1]) > 0)
635                      j++; // j indexes smallest kid
636                  if (comparator.compare((E)queue[k], (E)queue[j]) <= 0)
637                      break;
# Line 537 | Line 641 | public class PriorityQueue<E> extends Ab
641          }
642      }
643  
644 +    /**
645 +     * Establishes the heap invariant (described above) in the entire tree,
646 +     * assuming nothing about the order of the elements prior to the call.
647 +     */
648 +    private void heapify() {
649 +        for (int i = size/2; i >= 1; i--)
650 +            fixDown(i);
651 +    }
652  
653      /**
654 <     * Returns the comparator used to order this collection, or <tt>null</tt>
655 <     * if this collection is sorted according to its elements natural ordering
656 <     * (using <tt>Comparable</tt>).
657 <     *
658 <     * @return the comparator used to order this collection, or <tt>null</tt>
659 <     * if this collection is sorted according to its elements natural ordering.
654 >     * Returns the comparator used to order the elements in this
655 >     * queue, or <tt>null</tt> if this queue is sorted according to
656 >     * the {@linkplain Comparable natural ordering} of its elements.
657 >     *
658 >     * @return the comparator used to order this queue, or
659 >     *         <tt>null</tt> if this queue is sorted according to the
660 >     *         natural ordering of its elements.
661       */
662      public Comparator<? super E> comparator() {
663          return comparator;
# Line 568 | Line 681 | public class PriorityQueue<E> extends Ab
681          s.writeInt(queue.length);
682  
683          // Write out all elements in the proper order.
684 <        for (int i=0; i<size; i++)
684 >        for (int i=1; i<=size; i++)
685              s.writeObject(queue[i]);
686      }
687  
688      /**
689 <     * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
690 <     * deserialize it).
689 >     * Reconstitute the <tt>PriorityQueue</tt> instance from a stream
690 >     * (that is, deserialize it).
691       * @param s the stream
692       */
693      private void readObject(java.io.ObjectInputStream s)
# Line 587 | Line 700 | public class PriorityQueue<E> extends Ab
700          queue = new Object[arrayLength];
701  
702          // Read in all elements in the proper order.
703 <        for (int i=0; i<size; i++)
704 <            queue[i] = s.readObject();
703 >        for (int i=1; i<=size; i++)
704 >            queue[i] = (E) s.readObject();
705      }
706  
707   }
595

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines