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.3 by tim, Sun May 18 20:36:01 2003 UTC vs.
Revision 1.56 by jsr166, Mon Nov 28 02:35:46 2005 UTC

# Line 1 | Line 1
1 package java.util;
2
1   /*
2 < * Todo
2 > * @(#)PriorityQueue.java       1.8 05/08/27
3   *
4 < *   1) Make it serializable.
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 the order specified at creation time.  This order is
14 < * specified as for {@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 < * these elements are tied for least value, no guarantees are made as to
20 < * which of 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>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 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 < {
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      /**
71 <     * Priority queue represented as a balanced binary heap: the two children
72 <     * of queue[n] are queue[2*n] and queue[2*n + 1].  The priority queue is
73 <     * ordered by comparator, or by the elements' natural ordering, if
74 <     * comparator is null:  For each node n in the heap, and each descendant
75 <     * of n, d, n <= d.
76 <     *
48 <     * The element with the lowest value is in queue[1] (assuming the queue is
49 <     * nonempty). A one-based array is used in preference to the traditional
50 <     * zero-based array to simplify parent and child calculations.
51 <     *
52 <     * queue.length must be >= 2, even if size == 0.
71 >     * Priority queue represented as a balanced binary heap: the two
72 >     * children of queue[n] are queue[2*n+1] and queue[2*(n+1)].  The
73 >     * priority queue is ordered by comparator, or by the elements'
74 >     * natural ordering, if comparator is null: For each node n in the
75 >     * heap and each descendant d of n, n <= d.  The element with the
76 >     * lowest value is in queue[0], assuming the queue is nonempty.
77       */
78 <    private E[] queue;
78 >    private transient Object[] queue;
79  
80      /**
81       * The number of elements in the priority queue.
# Line 62 | Line 86 | public class PriorityQueue<E> extends Ab
86       * The comparator, or null if priority queue uses elements'
87       * natural ordering.
88       */
89 <    private final Comparator<E> comparator;
89 >    private final Comparator<? super E> comparator;
90  
91      /**
92       * The number of times this priority queue has been
93       * <i>structurally modified</i>.  See AbstractList for gory details.
94       */
95 <    private int modCount = 0;
95 >    private transient int modCount = 0;
96  
97      /**
98 <     * Create a new priority queue with the default initial capacity (11)
99 <     * that orders its elements according to their natural ordering.
98 >     * Creates a <tt>PriorityQueue</tt> with the default initial
99 >     * capacity (11) that orders its elements according to their
100 >     * {@linkplain Comparable natural ordering}.
101       */
102      public PriorityQueue() {
103 <        this(DEFAULT_INITIAL_CAPACITY);
103 >        this(DEFAULT_INITIAL_CAPACITY, null);
104      }
105  
106      /**
107 <     * Create a new priority queue with the specified initial capacity
108 <     * that orders its elements according to their natural ordering.
107 >     * Creates a <tt>PriorityQueue</tt> with the specified initial
108 >     * capacity that orders its elements according to their
109 >     * {@linkplain Comparable natural ordering}.
110       *
111 <     * @param initialCapacity the initial capacity for this priority queue.
111 >     * @param initialCapacity the initial capacity for this priority queue
112 >     * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
113 >     * than 1
114       */
115      public PriorityQueue(int initialCapacity) {
116          this(initialCapacity, null);
117      }
118  
119      /**
120 <     * Create a new priority queue with the specified initial capacity (11)
120 >     * Creates a <tt>PriorityQueue</tt> with the specified initial capacity
121       * that orders its elements according to the specified comparator.
122       *
123 <     * @param initialCapacity the initial capacity for this priority queue.
124 <     * @param comparator the comparator used to order this priority queue.
125 <     */
126 <    public PriorityQueue(int initialCapacity, Comparator<E> comparator) {
123 >     * @param  initialCapacity the initial capacity for this priority queue
124 >     * @param  comparator the comparator that will be used to order
125 >     *         this priority queue.  If <tt>null</tt>, the <i>natural
126 >     *         ordering</i> of the elements will be used.
127 >     * @throws IllegalArgumentException if <tt>initialCapacity</tt> is
128 >     *         less than 1
129 >     */
130 >    public PriorityQueue(int initialCapacity,
131 >                         Comparator<? super E> comparator) {
132 >        // Note: This restriction of at least one is not actually needed,
133 >        // but continues for 1.5 compatibility
134          if (initialCapacity < 1)
135 <            initialCapacity = 1;
136 <        queue = new E[initialCapacity + 1];
135 >            throw new IllegalArgumentException();
136 >        this.queue = new Object[initialCapacity];
137          this.comparator = comparator;
138      }
139  
140      /**
141 <     * Create a new priority queue containing the elements in the specified
142 <     * collection.  The priority queue has an initial capacity of 110% of the
143 <     * size of the specified collection. If the specified collection
144 <     * implements the {@link Sorted} interface, the priority queue will be
145 <     * sorted according to the same comparator, or according to its elements'
146 <     * 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.
141 >     * Creates a <tt>PriorityQueue</tt> containing the elements in the
142 >     * specified collection.   If the specified collection is an
143 >     * instance of a {@link java.util.SortedSet} or is another
144 >     * <tt>PriorityQueue</tt>, the priority queue will be ordered
145 >     * according to the same ordering.  Otherwise, this priority queue
146 >     * will be ordered according to the natural ordering of its elements.
147       *
148 <     * @param initialElements the collection whose elements are to be placed
149 <     *        into this priority queue.
148 >     * @param  c the collection whose elements are to be placed
149 >     *         into this priority queue
150       * @throws ClassCastException if elements of the specified collection
151       *         cannot be compared to one another according to the priority
152 <     *         queue's ordering.
153 <     * @throws NullPointerException if the specified collection or an
154 <     *         element of the specified collection is <tt>null</tt>.
155 <     */
156 <    public PriorityQueue(Collection<E> initialElements) {
157 <        int sz = initialElements.size();
158 <        int initialCapacity = (int)Math.min((sz * 110L) / 100,
159 <                                            Integer.MAX_VALUE - 1);
160 <        if (initialCapacity < 1)
161 <            initialCapacity = 1;
162 <        queue = new E[initialCapacity + 1];
163 <
164 <        /* Commented out to compile with generics compiler
133 <
134 <        if (initialElements instanceof Sorted) {
135 <            comparator = ((Sorted)initialElements).comparator();
136 <            for (Iterator<E> i = initialElements.iterator(); i.hasNext(); )
137 <                queue[++size] = i.next();
138 <        } else {
139 <        */
140 <        {
152 >     *         queue's ordering
153 >     * @throws NullPointerException if the specified collection or any
154 >     *         of its elements are null
155 >     */
156 >    public PriorityQueue(Collection<? extends E> c) {
157 >        initFromCollection(c);
158 >        if (c instanceof SortedSet)
159 >            comparator = (Comparator<? super E>)
160 >                ((SortedSet<? extends E>)c).comparator();
161 >        else if (c instanceof PriorityQueue)
162 >            comparator = (Comparator<? super E>)
163 >                ((PriorityQueue<? extends E>)c).comparator();
164 >        else {
165              comparator = null;
166 <            for (Iterator<E> i = initialElements.iterator(); i.hasNext(); )
143 <                add(i.next());
166 >            heapify();
167          }
168      }
169  
170 <    // Queue Methods
170 >    /**
171 >     * Creates a <tt>PriorityQueue</tt> containing the elements in the
172 >     * specified priority queue.  This priority queue will be
173 >     * ordered according to the same ordering as the given priority
174 >     * queue.
175 >     *
176 >     * @param  c the priority queue whose elements are to be placed
177 >     *         into this priority queue
178 >     * @throws ClassCastException if elements of <tt>c</tt> cannot be
179 >     *         compared to one another according to <tt>c</tt>'s
180 >     *         ordering
181 >     * @throws NullPointerException if the specified priority queue or any
182 >     *         of its elements are null
183 >     */
184 >    public PriorityQueue(PriorityQueue<? extends E> c) {
185 >        comparator = (Comparator<? super E>)c.comparator();
186 >        initFromCollection(c);
187 >    }
188  
189      /**
190 <     * Remove and return the minimal element from this priority queue if
191 <     * it contains one or more elements, otherwise <tt>null</tt>.  The term
192 <     * <i>minimal</i> is defined according to this priority queue's order.
190 >     * Creates a <tt>PriorityQueue</tt> containing the elements in the
191 >     * specified sorted set.  This priority queue will be ordered
192 >     * according to the same ordering as the given sorted set.
193       *
194 <     * @return the minimal element from this priority queue if it contains
195 <     *         one or more elements, otherwise <tt>null</tt>.
194 >     * @param  c the sorted set whose elements are to be placed
195 >     *         into this priority queue.
196 >     * @throws ClassCastException if elements of the specified sorted
197 >     *         set cannot be compared to one another according to the
198 >     *         sorted set's ordering
199 >     * @throws NullPointerException if the specified sorted set or any
200 >     *         of its elements are null
201       */
202 <    public E poll() {
203 <        if (size == 0)
204 <            return null;
160 <        return remove(1);
202 >    public PriorityQueue(SortedSet<? extends E> c) {
203 >        comparator = (Comparator<? super E>)c.comparator();
204 >        initFromCollection(c);
205      }
206  
207      /**
208 <     * Return, but do not remove, the minimal element from the priority queue,
209 <     * or <tt>null</tt> if the queue is empty.  The term <i>minimal</i> is
210 <     * defined according to this priority queue's order.  This method returns
211 <     * the same object reference that would be returned by by the
212 <     * <tt>poll</tt> method.  The two methods differ in that this method
213 <     * does not remove the element from the priority queue.
208 >     * Initialize queue array with elements from the given Collection.
209 >     * @param c the collection
210 >     */
211 >    private void initFromCollection(Collection<? extends E> c) {
212 >        Object[] a = c.toArray();
213 >        // If c.toArray incorrectly doesn't return Object[], copy it.
214 >        if (a.getClass() != Object[].class)
215 >            a = Arrays.copyOf(a, a.length, Object[].class);
216 >        queue = a;
217 >        size = a.length;
218 >    }
219 >
220 >    /**
221 >     * Increases the capacity of the array.
222       *
223 <     * @return the minimal element from this priority queue if it contains
172 <     *         one or more elements, otherwise <tt>null</tt>.
223 >     * @param minCapacity the desired minimum capacity
224       */
225 <    public E peek() {
226 <        return queue[1];
225 >    private void grow(int minCapacity) {
226 >        if (minCapacity < 0) // overflow
227 >            throw new OutOfMemoryError();
228 >        int oldCapacity = queue.length;
229 >        // Double size if small; else grow by 50%
230 >        int newCapacity = ((oldCapacity < 64)?
231 >                           ((oldCapacity + 1) * 2):
232 >                           ((oldCapacity * 3) / 2));
233 >        if (newCapacity < minCapacity)
234 >            newCapacity = minCapacity;
235 >        queue = Arrays.copyOf(queue, newCapacity);
236      }
237  
238 <    // Collection Methods
238 >    /**
239 >     * Inserts the specified element into this priority queue.
240 >     *
241 >     * @return <tt>true</tt> (as specified by {@link Collection#add})
242 >     * @throws ClassCastException if the specified element cannot be
243 >     *         compared with elements currently in this priority queue
244 >     *         according to the priority queue's ordering
245 >     * @throws NullPointerException if the specified element is null
246 >     */
247 >    public boolean add(E e) {
248 >        return offer(e);
249 >    }
250  
251      /**
252 <     * Removes a single instance of the specified element from this priority
182 <     * queue, if it is present.  Returns true if this collection contained the
183 <     * specified element (or equivalently, if this collection changed as a
184 <     * result of the call).
252 >     * Inserts the specified element into this priority queue.
253       *
254 <     * @param o element to be removed from this collection, if present.
255 <     * @return <tt>true</tt> if this collection changed as a result of the
256 <     *         call
257 <     * @throws ClassCastException if the specified element cannot be compared
258 <     *            with elements currently in the priority queue according
191 <     *            to the priority queue's ordering.
192 <     * @throws NullPointerException if the specified element is null.
254 >     * @return <tt>true</tt> (as specified by {@link Queue#offer})
255 >     * @throws ClassCastException if the specified element cannot be
256 >     *         compared with elements currently in this priority queue
257 >     *         according to the priority queue's ordering
258 >     * @throws NullPointerException if the specified element is null
259       */
260 <    public boolean remove(Object element) {
261 <        if (element == null)
260 >    public boolean offer(E e) {
261 >        if (e == null)
262              throw new NullPointerException();
263 +        modCount++;
264 +        int i = size;
265 +        if (i >= queue.length)
266 +            grow(i + 1);
267 +        size = i + 1;
268 +        if (i == 0)
269 +            queue[0] = e;
270 +        else
271 +            siftUp(i, e);
272 +        return true;
273 +    }
274  
275 <        if (comparator == null) {
276 <            for (int i = 1; i <= size; i++) {
277 <                if (((Comparable)queue[i]).compareTo(element) == 0) {
278 <                    remove(i);
279 <                    return true;
280 <                }
281 <            }
282 <        } else {
283 <            for (int i = 1; i <= size; i++) {
284 <                if (comparator.compare(queue[i], (E) element) == 0) {
285 <                    remove(i);
286 <                    return true;
287 <                }
275 >    public E peek() {
276 >        if (size == 0)
277 >            return null;
278 >        return (E) queue[0];
279 >    }
280 >
281 >    private int indexOf(Object o) {
282 >        if (o != null) {
283 >            for (int i = 0; i < size; i++)
284 >                if (o.equals(queue[i]))
285 >                    return i;
286 >        }
287 >        return -1;
288 >    }
289 >
290 >    /**
291 >     * Removes a single instance of the specified element from this queue,
292 >     * if it is present.  More formally, removes an element <tt>e</tt> such
293 >     * that <tt>o.equals(e)</tt>, if this queue contains one or more such
294 >     * elements.  Returns true if this queue contained the specified element
295 >     * (or equivalently, if this queue changed as a result of the call).
296 >     *
297 >     * @param o element to be removed from this queue, if present
298 >     * @return <tt>true</tt> if this queue changed as a result of the call
299 >     */
300 >    public boolean remove(Object o) {
301 >        int i = indexOf(o);
302 >        if (i == -1)
303 >            return false;
304 >        else {
305 >            removeAt(i);
306 >            return true;
307 >        }
308 >    }
309 >
310 >    /**
311 >     * Version of remove using reference equality, not equals.
312 >     * Needed by iterator.remove
313 >     *
314 >     * @param o element to be removed from this queue, if present
315 >     * @return <tt>true</tt> if removed.
316 >     */
317 >    boolean removeEq(Object o) {
318 >        for (int i = 0; i < size; i++) {
319 >            if (o == queue[i]) {
320 >                removeAt(i);
321 >                return true;
322              }
323          }
324          return false;
325      }
326  
327      /**
328 <     * Returns an iterator over the elements in this priority queue.  The
329 <     * first element returned by this iterator is the same element that
330 <     * would be returned by a call to <tt>peek</tt>.
328 >     * Returns <tt>true</tt> if this queue contains the specified element.
329 >     * More formally, returns <tt>true</tt> if and only if this queue contains
330 >     * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
331 >     *
332 >     * @param o object to be checked for containment in this queue
333 >     * @return <tt>true</tt> if this queue contains the specified element
334 >     */
335 >    public boolean contains(Object o) {
336 >        return indexOf(o) != -1;
337 >    }
338 >
339 >    /**
340 >     * Returns an array containing all of the elements in this queue,
341 >     * The elements are in no particular order.
342 >     *
343 >     * <p>The returned array will be "safe" in that no references to it are
344 >     * maintained by this list.  (In other words, this method must allocate
345 >     * a new array).  The caller is thus free to modify the returned array.
346       *
347 <     * @return an <tt>Iterator</tt> over the elements in this priority queue.
347 >     * @return an array containing all of the elements in this queue.
348 >     */
349 >    public Object[] toArray() {
350 >        return Arrays.copyOf(queue, size);
351 >    }
352 >
353 >    /**
354 >     * Returns an array containing all of the elements in this queue.
355 >     * The elements are in no particular order.  The runtime type of
356 >     * the returned array is that of the specified array.  If the queue
357 >     * fits in the specified array, it is returned therein.
358 >     * Otherwise, a new array is allocated with the runtime type of
359 >     * the specified array and the size of this queue.
360 >     *
361 >     * <p>If the queue fits in the specified array with room to spare
362 >     * (i.e., the array has more elements than the queue), the element in
363 >     * the array immediately following the end of the collection is set to
364 >     * <tt>null</tt>.  (This is useful in determining the length of the
365 >     * queue <i>only</i> if the caller knows that the queue does not contain
366 >     * any null elements.)
367 >     *
368 >     * @param a the array into which the elements of the queue are to
369 >     *          be stored, if it is big enough; otherwise, a new array of the
370 >     *          same runtime type is allocated for this purpose.
371 >     * @return an array containing the elements of the queue
372 >     * @throws ArrayStoreException if the runtime type of the specified array
373 >     *         is not a supertype of the runtime type of every element in
374 >     *         this queue
375 >     * @throws NullPointerException if the specified array is null
376 >     */
377 >    public <T> T[] toArray(T[] a) {
378 >        if (a.length < size)
379 >            // Make a new array of a's runtime type, but my contents:
380 >            return (T[]) Arrays.copyOf(queue, size, a.getClass());
381 >        System.arraycopy(queue, 0, a, 0, size);
382 >        if (a.length > size)
383 >            a[size] = null;
384 >        return a;
385 >    }
386 >
387 >    /**
388 >     * Returns an iterator over the elements in this queue. The iterator
389 >     * does not return the elements in any particular order.
390 >     *
391 >     * @return an iterator over the elements in this queue
392       */
393      public Iterator<E> iterator() {
394          return new Itr();
395      }
396  
397 <    private class Itr implements Iterator<E> {
397 >    private final class Itr implements Iterator<E> {
398          /**
399           * Index (into queue array) of element to be returned by
400           * subsequent call to next.
401           */
402 <        int cursor = 1;
402 >        private int cursor = 0;
403 >
404 >        /**
405 >         * Index of element returned by most recent call to next,
406 >         * unless that element came from the forgetMeNot list.
407 >         * Set to -1 if element is deleted by a call to remove.
408 >         */
409 >        private int lastRet = -1;
410 >
411 >        /**
412 >         * A queue of elements that were moved from the unvisited portion of
413 >         * the heap into the visited portion as a result of "unlucky" element
414 >         * removals during the iteration.  (Unlucky element removals are those
415 >         * that require a siftup instead of a siftdown.)  We must visit all of
416 >         * the elements in this list to complete the iteration.  We do this
417 >         * after we've completed the "normal" iteration.
418 >         *
419 >         * We expect that most iterations, even those involving removals,
420 >         * will not use need to store elements in this field.
421 >         */
422 >        private ArrayDeque<E> forgetMeNot = null;
423  
424          /**
425 <         * Index of element returned by most recent call to next or
426 <         * previous.  Reset to 0 if this element is deleted by a call
237 <         * to remove.
425 >         * Element returned by the most recent call to next iff that
426 >         * element was drawn from the forgetMeNot list.
427           */
428 <        int lastRet = 0;
428 >        private E lastRetElt = null;
429  
430          /**
431           * The modCount value that the iterator believes that the backing
432           * List should have.  If this expectation is violated, the iterator
433           * has detected concurrent modification.
434           */
435 <        int expectedModCount = modCount;
435 >        private int expectedModCount = modCount;
436  
437          public boolean hasNext() {
438 <            return cursor <= size;
438 >            return cursor < size ||
439 >                (forgetMeNot != null && !forgetMeNot.isEmpty());
440          }
441  
442          public E next() {
443 <            checkForComodification();
444 <            if (cursor > size)
445 <                throw new NoSuchElementException();
446 <            E result = queue[cursor];
447 <            lastRet = cursor++;
448 <            return result;
443 >            if (expectedModCount != modCount)
444 >                throw new ConcurrentModificationException();
445 >            if (cursor < size)
446 >                return (E) queue[lastRet = cursor++];
447 >            if (forgetMeNot != null) {
448 >                lastRet = -1;
449 >                lastRetElt = forgetMeNot.poll();
450 >                if (lastRetElt != null)
451 >                    return lastRetElt;
452 >            }
453 >            throw new NoSuchElementException();
454          }
455  
456          public void remove() {
457 <            if (lastRet == 0)
457 >            if (expectedModCount != modCount)
458 >                throw new ConcurrentModificationException();
459 >            if (lastRet == -1 && lastRetElt == null)
460                  throw new IllegalStateException();
461 <            checkForComodification();
462 <
463 <            PriorityQueue.this.remove(lastRet);
464 <            if (lastRet < cursor)
465 <                cursor--;
466 <            lastRet = 0;
461 >            if (lastRet != -1) {
462 >                E moved = PriorityQueue.this.removeAt(lastRet);
463 >                lastRet = -1;
464 >                if (moved == null)
465 >                    cursor--;
466 >                else {
467 >                    if (forgetMeNot == null)
468 >                        forgetMeNot = new ArrayDeque<E>();
469 >                    forgetMeNot.add(moved);
470 >                }
471 >            } else {
472 >                PriorityQueue.this.removeEq(lastRetElt);
473 >                lastRetElt = null;
474 >            }
475              expectedModCount = modCount;
476          }
477  
273        final void checkForComodification() {
274            if (modCount != expectedModCount)
275                throw new ConcurrentModificationException();
276        }
478      }
479  
279    /**
280     * Returns the number of elements in this priority queue.
281     *
282     * @return the number of elements in this priority queue.
283     */
480      public int size() {
481          return size;
482      }
483  
484      /**
485 <     * Add the specified element to this priority queue.
486 <     *
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.
485 >     * Removes all of the elements from this priority queue.
486 >     * The queue will be empty after this call returns.
487       */
488 <    public boolean offer(E element) {
299 <        if (element == null)
300 <            throw new NullPointerException();
488 >    public void clear() {
489          modCount++;
490 +        for (int i = 0; i < size; i++)
491 +            queue[i] = null;
492 +        size = 0;
493 +    }
494  
495 <        // Grow backing store if necessary
496 <        if (++size == queue.length) {
497 <            E[] newQueue = new E[2 * queue.length];
498 <            System.arraycopy(queue, 0, newQueue, 0, size);
499 <            queue = newQueue;
500 <        }
501 <
502 <        queue[size] = element;
503 <        fixUp(size);
504 <        return true;
495 >    public E poll() {
496 >        if (size == 0)
497 >            return null;
498 >        int s = --size;
499 >        modCount++;
500 >        E result = (E)queue[0];
501 >        E x = (E)queue[s];
502 >        queue[s] = null;
503 >        if (s != 0)
504 >            siftDown(0, x);
505 >        return result;
506      }
507  
508      /**
509 <     * Remove all elements from the priority queue.
509 >     * Removes the ith element from queue.
510 >     *
511 >     * Normally this method leaves the elements at up to i-1,
512 >     * inclusive, untouched.  Under these circumstances, it returns
513 >     * null.  Occasionally, in order to maintain the heap invariant,
514 >     * it must swap a later element of the list with one earlier than
515 >     * i.  Under these circumstances, this method returns the element
516 >     * that was previously at the end of the list and is now at some
517 >     * position before i. This fact is used by iterator.remove so as to
518 >     * avoid missing traverseing elements.
519       */
520 <    public void clear() {
520 >    private E removeAt(int i) {
521 >        assert i >= 0 && i < size;
522          modCount++;
523 <
524 <        // Null out element references to prevent memory leak
322 <        for (int i=1; i<=size; i++)
523 >        int s = --size;
524 >        if (s == i) // removed last element
525              queue[i] = null;
526 <
527 <        size = 0;
526 >        else {
527 >            E moved = (E) queue[s];
528 >            queue[s] = null;
529 >            siftDown(i, moved);
530 >            if (queue[i] == moved) {
531 >                siftUp(i, moved);
532 >                if (queue[i] != moved)
533 >                    return moved;
534 >            }
535 >        }
536 >        return null;
537      }
538  
539      /**
540 <     * Removes and returns the ith element from queue.  Recall
541 <     * that queue is one-based, so 1 <= i <= size.
540 >     * Inserts item x at position k, maintaining heap invariant by
541 >     * promoting x up the tree until it is greater than or equal to
542 >     * its parent, or is the root.
543       *
544 <     * XXX: Could further special-case i==size, but is it worth it?
545 <     * XXX: Could special-case i==0, but is it worth it?
544 >     * To simplify and speed up coercions and comparisons. the
545 >     * Comparable and Comparator versions are separated into different
546 >     * methods that are otherwise identical. (Similarly for siftDown.)
547 >     *
548 >     * @param k the position to fill
549 >     * @param x the item to insert
550       */
551 <    private E remove(int i) {
552 <        assert i <= size;
553 <        modCount++;
551 >    private void siftUp(int k, E x) {
552 >        if (comparator != null)
553 >            siftUpUsingComparator(k, x);
554 >        else
555 >            siftUpComparable(k, x);
556 >    }
557  
558 <        E result = queue[i];
559 <        queue[i] = queue[size];
560 <        queue[size--] = null;  // Drop extra ref to prevent memory leak
561 <        if (i <= size)
562 <            fixDown(i);
563 <        return result;
558 >    private void siftUpComparable(int k, E x) {
559 >        Comparable<? super E> key = (Comparable<? super E>) x;
560 >        while (k > 0) {
561 >            int parent = (k - 1) >>> 1;
562 >            Object e = queue[parent];
563 >            if (key.compareTo((E)e) >= 0)
564 >                break;
565 >            queue[k] = e;
566 >            k = parent;
567 >        }
568 >        queue[k] = key;
569      }
570  
571 <    /**
572 <     * Establishes the heap invariant (described above) assuming the heap
573 <     * satisfies the invariant except possibly for the leaf-node indexed by k
574 <     * (which may have a nextExecutionTime less than its parent's).
575 <     *
576 <     * This method functions by "promoting" queue[k] up the hierarchy
577 <     * (by swapping it with its parent) repeatedly until queue[k]
578 <     * is greater than or equal to its parent.
355 <     */
356 <    private void fixUp(int k) {
357 <        if (comparator == null) {
358 <            while (k > 1) {
359 <                int j = k >> 1;
360 <                if (((Comparable)queue[j]).compareTo(queue[k]) <= 0)
361 <                    break;
362 <                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
363 <                k = j;
364 <            }
365 <        } else {
366 <            while (k > 1) {
367 <                int j = k >> 1;
368 <                if (comparator.compare(queue[j], queue[k]) <= 0)
369 <                    break;
370 <                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
371 <                k = j;
372 <            }
571 >    private void siftUpUsingComparator(int k, E x) {
572 >        while (k > 0) {
573 >            int parent = (k - 1) >>> 1;
574 >            Object e = queue[parent];
575 >            if (comparator.compare(x, (E)e) >= 0)
576 >                break;
577 >            queue[k] = e;
578 >            k = parent;
579          }
580 +        queue[k] = x;
581      }
582  
583      /**
584 <     * Establishes the heap invariant (described above) in the subtree
585 <     * rooted at k, which is assumed to satisfy the heap invariant except
586 <     * possibly for node k itself (which may be greater than its children).
587 <     *
588 <     * This method functions by "demoting" queue[k] down the hierarchy
589 <     * (by swapping it with its smaller child) repeatedly until queue[k]
590 <     * is less than or equal to its children.
591 <     */
592 <    private void fixDown(int k) {
593 <        int j;
594 <        if (comparator == null) {
595 <            while ((j = k << 1) <= size) {
596 <                if (j<size && ((Comparable)queue[j]).compareTo(queue[j+1]) > 0)
597 <                    j++; // j indexes smallest kid
598 <                if (((Comparable)queue[k]).compareTo(queue[j]) <= 0)
599 <                    break;
600 <                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
601 <                k = j;
602 <            }
603 <        } else {
604 <            while ((j = k << 1) <= size) {
605 <                if (j < size && comparator.compare(queue[j], queue[j+1]) > 0)
606 <                    j++; // j indexes smallest kid
607 <                if (comparator.compare(queue[k], queue[j]) <= 0)
608 <                    break;
609 <                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
610 <                k = j;
611 <            }
584 >     * Inserts item x at position k, maintaining heap invariant by
585 >     * demoting x down the tree repeatedly until it is less than or
586 >     * equal to its children or is a leaf.
587 >     *
588 >     * @param k the position to fill
589 >     * @param x the item to insert
590 >     */
591 >    private void siftDown(int k, E x) {
592 >        if (comparator != null)
593 >            siftDownUsingComparator(k, x);
594 >        else
595 >            siftDownComparable(k, x);
596 >    }
597 >
598 >    private void siftDownComparable(int k, E x) {
599 >        Comparable<? super E> key = (Comparable<? super E>)x;
600 >        int half = size >>> 1;        // loop while a non-leaf
601 >        while (k < half) {
602 >            int child = (k << 1) + 1; // assume left child is least
603 >            Object c = queue[child];
604 >            int right = child + 1;
605 >            if (right < size &&
606 >                ((Comparable<? super E>)c).compareTo((E)queue[right]) > 0)
607 >                c = queue[child = right];
608 >            if (key.compareTo((E)c) <= 0)
609 >                break;
610 >            queue[k] = c;
611 >            k = child;
612          }
613 +        queue[k] = key;
614 +    }
615 +
616 +    private void siftDownUsingComparator(int k, E x) {
617 +        int half = size >>> 1;
618 +        while (k < half) {
619 +            int child = (k << 1) + 1;
620 +            Object c = queue[child];
621 +            int right = child + 1;
622 +            if (right < size &&
623 +                comparator.compare((E)c, (E)queue[right]) > 0)
624 +                c = queue[child = right];
625 +            if (comparator.compare(x, (E)c) <= 0)
626 +                break;
627 +            queue[k] = c;
628 +            k = child;
629 +        }
630 +        queue[k] = x;
631 +    }
632 +
633 +    /**
634 +     * Establishes the heap invariant (described above) in the entire tree,
635 +     * assuming nothing about the order of the elements prior to the call.
636 +     */
637 +    private void heapify() {
638 +        for (int i = (size >>> 1) - 1; i >= 0; i--)
639 +            siftDown(i, (E)queue[i]);
640      }
641  
642      /**
643 <     * Returns the comparator associated with this priority queue, or
644 <     * <tt>null</tt> if it uses its elements' natural ordering.
643 >     * Returns the comparator used to order the elements in this
644 >     * queue, or <tt>null</tt> if this queue is sorted according to
645 >     * the {@linkplain Comparable natural ordering} of its elements.
646       *
647 <     * @return the comparator associated with this priority queue, or
648 <     *         <tt>null</tt> if it uses its elements' natural ordering.
647 >     * @return the comparator used to order this queue, or
648 >     *         <tt>null</tt> if this queue is sorted according to the
649 >     *         natural ordering of its elements.
650       */
651 <    Comparator<E> comparator() {
651 >    public Comparator<? super E> comparator() {
652          return comparator;
653      }
654 +
655 +    /**
656 +     * Save the state of the instance to a stream (that
657 +     * is, serialize it).
658 +     *
659 +     * @serialData The length of the array backing the instance is
660 +     * emitted (int), followed by all of its elements (each an
661 +     * <tt>Object</tt>) in the proper order.
662 +     * @param s the stream
663 +     */
664 +    private void writeObject(java.io.ObjectOutputStream s)
665 +        throws java.io.IOException{
666 +        // Write out element count, and any hidden stuff
667 +        s.defaultWriteObject();
668 +
669 +        // Write out array length
670 +        // For compatibility with 1.5 version, must be at least 2.
671 +        s.writeInt(Math.max(2, queue.length));
672 +
673 +        // Write out all elements in the proper order.
674 +        for (int i=0; i<size; i++)
675 +            s.writeObject(queue[i]);
676 +    }
677 +
678 +    /**
679 +     * Reconstitute the <tt>PriorityQueue</tt> instance from a stream
680 +     * (that is, deserialize it).
681 +     * @param s the stream
682 +     */
683 +    private void readObject(java.io.ObjectInputStream s)
684 +        throws java.io.IOException, ClassNotFoundException {
685 +        // Read in size, and any hidden stuff
686 +        s.defaultReadObject();
687 +
688 +        // Read in array length and allocate array
689 +        int arrayLength = s.readInt();
690 +        queue = new Object[arrayLength];
691 +
692 +        // Read in all elements in the proper order.
693 +        for (int i=0; i<size; i++)
694 +            queue[i] = (E) s.readObject();
695 +    }
696 +
697   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines