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.53 by jsr166, Wed Nov 23 05:33:25 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 queue based on a priority heap.  This queue orders
13 < * elements according to an order specified at construction time, which is
14 < * specified in the same manner as {@link TreeSet} and {@link TreeMap}: elements are ordered
15 < * either according to their <i>natural order</i> (see {@link Comparable}), or
16 < * according to a {@link Comparator}, depending on which constructor is used.
17 < * The {@link #peek}, {@link #poll}, and {@link #remove} methods return the
18 < * minimal element with respect to the specified ordering.  If multiple
19 < * elements are tied for least value, no guarantees are made as to
20 < * which of these elements is returned.
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 <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>A priority queue has a <i>capacity</i>.  The capacity is the
29 < * size of the array used internally to store the elements on the
30 < * queue.  It is always at least as large as the queue size.  As
31 < * elements are added to a priority queue, its capacity grows
32 < * automatically.  The details of the growth policy are not specified.
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
36 < *for the insertion methods (<tt>offer</tt>, <tt>poll</tt>,
37 < *<tt>remove()</tt> and <tt>add</tt>) methods; linear time for the
38 < *<tt>remove(Object)</tt> and <tt>contains(Object)</tt> methods; and
39 < *constant time for the retrieval methods (<tt>peek</tt>,
40 < *<tt>element</tt>, and <tt>size</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>
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 > * <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 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>,
65 <                                         java.io.Serializable {
64 >    implements java.io.Serializable {
65 >
66 >    private static final long serialVersionUID = -7720805057305804111L;
67 >
68      private static final int DEFAULT_INITIAL_CAPACITY = 11;
69  
70      /**
# Line 48 | Line 80 | public class PriorityQueue<E> extends Ab
80       *
81       * queue.length must be >= 2, even if size == 0.
82       */
83 <    private transient E[] queue;
83 >    private transient Object[] queue;
84  
85      /**
86       * The number of elements in the priority queue.
# Line 59 | Line 91 | public class PriorityQueue<E> extends Ab
91       * The comparator, or null if priority queue uses elements'
92       * natural ordering.
93       */
94 <    private final Comparator<E> comparator;
94 >    private final Comparator<? super E> comparator;
95  
96      /**
97       * The number of times this priority queue has been
# Line 68 | Line 100 | public class PriorityQueue<E> extends Ab
100      private transient int modCount = 0;
101  
102      /**
103 <     * Create a new priority queue 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);
108 >        this(DEFAULT_INITIAL_CAPACITY, null);
109      }
110  
111      /**
112 <     * Create a new priority queue 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       */
120      public PriorityQueue(int initialCapacity) {
121          this(initialCapacity, null);
122      }
123  
124      /**
125 <     * Create a new priority queue with the specified initial capacity (11)
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.
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, Comparator<E> comparator) {
135 >    public PriorityQueue(int initialCapacity,
136 >                         Comparator<? super E> comparator) {
137          if (initialCapacity < 1)
138 <            initialCapacity = 1;
139 <        queue = (E[]) new Object[initialCapacity + 1];
138 >            throw new IllegalArgumentException();
139 >        this.queue = new Object[initialCapacity + 1];
140          this.comparator = comparator;
141      }
142  
143      /**
144 <     * Create a new priority queue containing the elements in the specified
145 <     * 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>.
144 >     * Common code to initialize underlying queue array across
145 >     * constructors below.
146       */
147 <    public PriorityQueue(Collection<E> initialElements) {
148 <        int sz = initialElements.size();
147 >    private void initializeArray(Collection<? extends E> c) {
148 >        int sz = c.size();
149          int initialCapacity = (int)Math.min((sz * 110L) / 100,
150                                              Integer.MAX_VALUE - 1);
151          if (initialCapacity < 1)
152              initialCapacity = 1;
129        queue = (E[]) new Object[initialCapacity + 1];
153  
154 +        this.queue = new Object[initialCapacity + 1];
155 +    }
156 +
157 +    /**
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 in the order presented.
161 +     */
162 +    private void fillFromSorted(Collection<? extends E> c) {
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 +
171 +    /**
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 +            int k = ++size;
179 +            if (k >= queue.length)
180 +                grow(k);
181 +            queue[k] = i.next();
182 +        }
183 +        heapify();
184 +    }
185  
186 <        if (initialElements instanceof Sorted) {
187 <            comparator = ((Sorted)initialElements).comparator();
188 <            for (Iterator<E> i = initialElements.iterator(); i.hasNext(); )
189 <                queue[++size] = i.next();
186 >    /**
187 >     * Creates a <tt>PriorityQueue</tt> containing the elements in the
188 >     * specified collection.  The priority queue has an initial
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 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
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 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 >            SortedSet<? extends E> s = (SortedSet<? extends E>)c;
208 >            comparator = (Comparator<? super E>)s.comparator();
209 >            fillFromSorted(s);
210 >        } else if (c instanceof PriorityQueue) {
211 >            PriorityQueue<? extends E> s = (PriorityQueue<? extends E>) c;
212 >            comparator = (Comparator<? super E>)s.comparator();
213 >            fillFromSorted(s);
214          } else {
215              comparator = null;
216 <            for (Iterator<E> i = initialElements.iterator(); i.hasNext(); )
217 <                add(i.next());
216 >            fillFromUnsorted(c);
217 >        }
218 >    }
219 >
220 >    /**
221 >     * Creates a <tt>PriorityQueue</tt> containing the elements in the
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);
238 >        comparator = (Comparator<? super E>)c.comparator();
239 >        fillFromSorted(c);
240 >    }
241 >
242 >    /**
243 >     * Creates a <tt>PriorityQueue</tt> containing the elements in the
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);
259 >        comparator = (Comparator<? super E>)c.comparator();
260 >        fillFromSorted(c);
261 >    }
262 >
263 >    /**
264 >     * Resize array, if necessary, to be able to hold given index.
265 >     */
266 >    private void grow(int index) {
267 >        int newlen = queue.length;
268 >        if (index < newlen) // don't need to grow
269 >            return;
270 >        if (index == Integer.MAX_VALUE)
271 >            throw new OutOfMemoryError();
272 >        while (newlen <= index) {
273 >            if (newlen >= Integer.MAX_VALUE / 2)  // avoid overflow
274 >                newlen = Integer.MAX_VALUE;
275 >            else
276 >                newlen <<= 2;
277          }
278 +        queue = Arrays.copyOf(queue, newlen);
279      }
280  
281 <    // Queue Methods
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 <     * Remove and return the minimal element from this priority queue
147 <     * if it contains one or more elements, otherwise return
148 <     * <tt>null</tt>.  The term <i>minimal</i> is defined according to
149 <     * this priority queue's order.
295 >     * Inserts the specified element into this priority queue.
296       *
297 <     * @return the minimal element from this priority queue if it contains
298 <     *         one or more elements, otherwise <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 E poll() {
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)
311 >            grow(size);
312 >
313 >        queue[size] = e;
314 >        fixUp(size);
315 >        return true;
316 >    }
317 >
318 >    public E peek() {
319          if (size == 0)
320              return null;
321 <        return remove(1);
321 >        return (E) queue[1];
322 >    }
323 >
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 <     * Return, but do not remove, the minimal element from the
335 <     * priority queue, or return <tt>null</tt> if the queue is empty.
336 <     * The term <i>minimal</i> is defined according to this priority
337 <     * queue's order.  This method returns the same object reference
338 <     * 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.
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 <     * @return the minimal element from this priority queue if it contains
341 <     *         one or more elements, otherwise <tt>null</tt>.
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 E peek() {
344 <        return queue[1];
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 <    // Collection Methods
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 priority
367 <     * queue, if it is present.  Returns true if this collection contained the
368 <     * specified element (or equivalently, if this collection changed as a
369 <     * result of the call).
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 <     * @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
188 <     * @throws ClassCastException if the specified element cannot be compared
189 <     *            with elements currently in the priority queue according
190 <     *            to the priority queue's ordering.
191 <     * @throws NullPointerException if the specified element is null.
373 >     * @return an array containing all of the elements in this queue.
374       */
375 <    public boolean remove(Object element) {
376 <        if (element == null)
377 <            throw new NullPointerException();
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)queue[i]).compareTo(element) == 0) {
382 <                    remove(i);
383 <                    return true;
384 <                }
385 <            }
386 <        } else {
387 <            for (int i = 1; i <= size; i++) {
388 <                if (comparator.compare(queue[i], (E) element) == 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 priority queue.  The
415 <     * 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>.
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 <tt>Iterator</tt> over the elements in this priority 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 232 | 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 245 | 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 = 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() {
262            if (lastRet == 0)
263                throw new IllegalStateException();
489              checkForComodification();
490  
491 <            PriorityQueue.this.remove(lastRet);
492 <            if (lastRet < cursor)
493 <                cursor--;
494 <            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 276 | Line 514 | public class PriorityQueue<E> extends Ab
514          }
515      }
516  
279    /**
280     * Returns the number of elements in this priority queue.
281     *
282     * @return the number of elements in this priority queue.
283     */
517      public int size() {
518          return size;
519      }
520  
521      /**
522 <     * Add the specified element to this priority queue.
523 <     *
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 <    /**
317 <     * 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 326 | 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 <     * XXX: Could further special-case i==size, but is it worth it?
554 <     * XXX: Could special-case i==0, but is it worth it?
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 = 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 358 | Line 590 | public class PriorityQueue<E> extends Ab
590          if (comparator == null) {
591              while (k > 1) {
592                  int j = k >> 1;
593 <                if (((Comparable)queue[j]).compareTo(queue[k]) <= 0)
593 >                if (((Comparable<? super E>)queue[j]).compareTo((E)queue[k]) <= 0)
594                      break;
595 <                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
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;
601 <                if (comparator.compare(queue[j], queue[k]) <= 0)
600 >                int j = k >>> 1;
601 >                if (comparator.compare((E)queue[j], (E)queue[k]) <= 0)
602                      break;
603 <                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
603 >                Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
604                  k = j;
605              }
606          }
# Line 386 | Line 618 | public class PriorityQueue<E> extends Ab
618      private void fixDown(int k) {
619          int j;
620          if (comparator == null) {
621 <            while ((j = k << 1) <= size) {
622 <                if (j<size && ((Comparable)queue[j]).compareTo(queue[j+1]) > 0)
621 >            while ((j = k << 1) <= size && (j > 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)queue[k]).compareTo(queue[j]) <= 0)
625 >
626 >                if (((Comparable<? super E>)queue[k]).compareTo((E)queue[j]) <= 0)
627                      break;
628 <                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
628 >                Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
629                  k = j;
630              }
631          } else {
632 <            while ((j = k << 1) <= size) {
633 <                if (j < size && comparator.compare(queue[j], queue[j+1]) > 0)
632 >            while ((j = k << 1) <= size && (j > 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(queue[k], queue[j]) <= 0)
636 >                if (comparator.compare((E)queue[k], (E)queue[j]) <= 0)
637                      break;
638 <                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
638 >                Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
639                  k = j;
640              }
641          }
642      }
643  
644      /**
645 <     * Returns the comparator associated with this priority queue, or
646 <     * <tt>null</tt> if it uses its elements' natural ordering.
412 <     *
413 <     * @return the comparator associated with this priority queue, or
414 <     *         <tt>null</tt> if it uses its elements' natural ordering.
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 <    public Comparator comparator() {
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 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;
664      }
665  
# Line 426 | Line 672 | public class PriorityQueue<E> extends Ab
672       * <tt>Object</tt>) in the proper order.
673       * @param s the stream
674       */
675 <    private synchronized void writeObject(java.io.ObjectOutputStream s)
675 >    private void writeObject(java.io.ObjectOutputStream s)
676          throws java.io.IOException{
677          // Write out element count, and any hidden stuff
678          s.defaultWriteObject();
# Line 435 | 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 synchronized void readObject(java.io.ObjectInputStream s)
693 >    private void readObject(java.io.ObjectInputStream s)
694          throws java.io.IOException, ClassNotFoundException {
695          // Read in size, and any hidden stuff
696          s.defaultReadObject();
697  
698          // Read in array length and allocate array
699          int arrayLength = s.readInt();
700 <        queue = (E[]) new Object[arrayLength];
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] = (E)s.readObject();
703 >        for (int i=1; i<=size; i++)
704 >            queue[i] = (E) s.readObject();
705      }
706  
707   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines