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.2 by tim, Sun May 18 18:10:02 2003 UTC vs.
Revision 1.45 by dl, Sun Oct 19 13:38:29 2003 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines