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.60 by jsr166, Mon Dec 5 02:56:59 2005 UTC vs.
Revision 1.123 by jsr166, Sun May 6 16:26:03 2018 UTC

# Line 1 | Line 1
1   /*
2 < * %W% %E%
2 > * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
3 > * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4   *
5 < * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
6 < * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
5 > * This code is free software; you can redistribute it and/or modify it
6 > * under the terms of the GNU General Public License version 2 only, as
7 > * published by the Free Software Foundation.  Oracle designates this
8 > * particular file as subject to the "Classpath" exception as provided
9 > * by Oracle in the LICENSE file that accompanied this code.
10 > *
11 > * This code is distributed in the hope that it will be useful, but WITHOUT
12 > * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 > * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 > * version 2 for more details (a copy is included in the LICENSE file that
15 > * accompanied this code).
16 > *
17 > * You should have received a copy of the GNU General Public License version
18 > * 2 along with this work; if not, write to the Free Software Foundation,
19 > * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 > *
21 > * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 > * or visit www.oracle.com if you need additional information or have any
23 > * questions.
24   */
25  
26   package java.util;
27 < import java.util.*; // for javadoc (till 6280605 is fixed)
27 >
28 > import java.util.function.Consumer;
29 > import jdk.internal.misc.SharedSecrets;
30  
31   /**
32 < * An unbounded priority {@linkplain Queue queue} based on a priority
33 < * heap.  The elements of the priority queue are ordered according to
34 < * their {@linkplain Comparable natural ordering}, or by a {@link
35 < * Comparator} provided at queue construction time, depending on which
36 < * constructor is used.  A priority queue does not permit
37 < * <tt>null</tt> elements.  A priority queue relying on natural
38 < * ordering also does not permit insertion of non-comparable objects
39 < * (doing so may result in <tt>ClassCastException</tt>).
32 > * An unbounded priority {@linkplain Queue queue} based on a priority heap.
33 > * The elements of the priority queue are ordered according to their
34 > * {@linkplain Comparable natural ordering}, or by a {@link Comparator}
35 > * provided at queue construction time, depending on which constructor is
36 > * used.  A priority queue does not permit {@code null} elements.
37 > * A priority queue relying on natural ordering also does not permit
38 > * insertion of non-comparable objects (doing so may result in
39 > * {@code ClassCastException}).
40   *
41   * <p>The <em>head</em> of this queue is the <em>least</em> element
42   * with respect to the specified ordering.  If multiple elements are
43   * tied for least value, the head is one of those elements -- ties are
44 < * broken arbitrarily.  The queue retrieval operations <tt>poll</tt>,
45 < * <tt>remove</tt>, <tt>peek</tt>, and <tt>element</tt> access the
44 > * broken arbitrarily.  The queue retrieval operations {@code poll},
45 > * {@code remove}, {@code peek}, and {@code element} access the
46   * element at the head of the queue.
47   *
48   * <p>A priority queue is unbounded, but has an internal
# Line 35 | Line 55 | import java.util.*; // for javadoc (till
55   * <p>This class and its iterator implement all of the
56   * <em>optional</em> methods of the {@link Collection} and {@link
57   * Iterator} interfaces.  The Iterator provided in method {@link
58 < * #iterator()} is <em>not</em> guaranteed to traverse the elements of
58 > * #iterator()} and the Spliterator provided in method {@link #spliterator()}
59 > * are <em>not</em> guaranteed to traverse the elements of
60   * the priority queue in any particular order. If you need ordered
61 < * traversal, consider using <tt>Arrays.sort(pq.toArray())</tt>.
61 > * traversal, consider using {@code Arrays.sort(pq.toArray())}.
62   *
63 < * <p> <strong>Note that this implementation is not synchronized.</strong>
64 < * Multiple threads should not access a <tt>PriorityQueue</tt>
65 < * instance concurrently if any of the threads modifies the list
66 < * structurally. Instead, use the thread-safe {@link
63 > * <p><strong>Note that this implementation is not synchronized.</strong>
64 > * Multiple threads should not access a {@code PriorityQueue}
65 > * instance concurrently if any of the threads modifies the queue.
66 > * Instead, use the thread-safe {@link
67   * java.util.concurrent.PriorityBlockingQueue} class.
68   *
69 < * <p>Implementation note: this implementation provides O(log(n)) time
70 < * for the insertion methods (<tt>offer</tt>, <tt>poll</tt>,
71 < * <tt>remove()</tt> and <tt>add</tt>) methods; linear time for the
72 < * <tt>remove(Object)</tt> and <tt>contains(Object)</tt> methods; and
73 < * constant time for the retrieval methods (<tt>peek</tt>,
74 < * <tt>element</tt>, and <tt>size</tt>).
69 > * <p>Implementation note: this implementation provides
70 > * O(log(n)) time for the enqueuing and dequeuing methods
71 > * ({@code offer}, {@code poll}, {@code remove()} and {@code add});
72 > * linear time for the {@code remove(Object)} and {@code contains(Object)}
73 > * methods; and constant time for the retrieval methods
74 > * ({@code peek}, {@code element}, and {@code size}).
75   *
76   * <p>This class is a member of the
77 < * <a href="{@docRoot}/../guide/collections/index.html">
77 > * <a href="{@docRoot}/java/util/package-summary.html#CollectionsFramework">
78   * Java Collections Framework</a>.
79 + *
80   * @since 1.5
81 < * @version 1.8, 08/27/05
82 < * @author Josh Bloch
61 < * @param <E> the type of elements held in this collection
81 > * @author Josh Bloch, Doug Lea
82 > * @param <E> the type of elements held in this queue
83   */
84   public class PriorityQueue<E> extends AbstractQueue<E>
85      implements java.io.Serializable {
# Line 75 | Line 96 | public class PriorityQueue<E> extends Ab
96       * heap and each descendant d of n, n <= d.  The element with the
97       * lowest value is in queue[0], assuming the queue is nonempty.
98       */
99 <    private transient Object[] queue;
99 >    transient Object[] queue; // non-private to simplify nested class access
100  
101      /**
102       * The number of elements in the priority queue.
103       */
104 <    private int size = 0;
104 >    int size;
105  
106      /**
107       * The comparator, or null if priority queue uses elements'
# Line 92 | Line 113 | public class PriorityQueue<E> extends Ab
113       * The number of times this priority queue has been
114       * <i>structurally modified</i>.  See AbstractList for gory details.
115       */
116 <    private transient int modCount = 0;
116 >    transient int modCount;     // non-private to simplify nested class access
117  
118      /**
119 <     * Creates a <tt>PriorityQueue</tt> with the default initial
119 >     * Creates a {@code PriorityQueue} with the default initial
120       * capacity (11) that orders its elements according to their
121       * {@linkplain Comparable natural ordering}.
122       */
# Line 104 | Line 125 | public class PriorityQueue<E> extends Ab
125      }
126  
127      /**
128 <     * Creates a <tt>PriorityQueue</tt> with the specified initial
128 >     * Creates a {@code PriorityQueue} with the specified initial
129       * capacity that orders its elements according to their
130       * {@linkplain Comparable natural ordering}.
131       *
132       * @param initialCapacity the initial capacity for this priority queue
133 <     * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
134 <     * than 1
133 >     * @throws IllegalArgumentException if {@code initialCapacity} is less
134 >     *         than 1
135       */
136      public PriorityQueue(int initialCapacity) {
137          this(initialCapacity, null);
138      }
139  
140      /**
141 <     * Creates a <tt>PriorityQueue</tt> with the specified initial capacity
141 >     * Creates a {@code PriorityQueue} with the default initial capacity and
142 >     * whose elements are ordered according to the specified comparator.
143 >     *
144 >     * @param  comparator the comparator that will be used to order this
145 >     *         priority queue.  If {@code null}, the {@linkplain Comparable
146 >     *         natural ordering} of the elements will be used.
147 >     * @since 1.8
148 >     */
149 >    public PriorityQueue(Comparator<? super E> comparator) {
150 >        this(DEFAULT_INITIAL_CAPACITY, comparator);
151 >    }
152 >
153 >    /**
154 >     * Creates a {@code PriorityQueue} with the specified initial capacity
155       * that orders its elements according to the specified comparator.
156       *
157       * @param  initialCapacity the initial capacity for this priority queue
158 <     * @param  comparator the comparator that will be used to order
159 <     *         this priority queue.  If <tt>null</tt>, the <i>natural
160 <     *         ordering</i> of the elements will be used.
161 <     * @throws IllegalArgumentException if <tt>initialCapacity</tt> is
158 >     * @param  comparator the comparator that will be used to order this
159 >     *         priority queue.  If {@code null}, the {@linkplain Comparable
160 >     *         natural ordering} of the elements will be used.
161 >     * @throws IllegalArgumentException if {@code initialCapacity} is
162       *         less than 1
163       */
164      public PriorityQueue(int initialCapacity,
# Line 138 | Line 172 | public class PriorityQueue<E> extends Ab
172      }
173  
174      /**
175 <     * Creates a <tt>PriorityQueue</tt> containing the elements in the
176 <     * specified collection.   If the specified collection is an
177 <     * instance of a {@link java.util.SortedSet} or is another
178 <     * <tt>PriorityQueue</tt>, the priority queue will be ordered
179 <     * according to the same ordering.  Otherwise, this priority queue
180 <     * will be ordered according to the natural ordering of its elements.
175 >     * Creates a {@code PriorityQueue} containing the elements in the
176 >     * specified collection.  If the specified collection is an instance of
177 >     * a {@link SortedSet} or is another {@code PriorityQueue}, this
178 >     * priority queue will be ordered according to the same ordering.
179 >     * Otherwise, this priority queue will be ordered according to the
180 >     * {@linkplain Comparable natural ordering} of its elements.
181       *
182       * @param  c the collection whose elements are to be placed
183       *         into this priority queue
# Line 153 | Line 187 | public class PriorityQueue<E> extends Ab
187       * @throws NullPointerException if the specified collection or any
188       *         of its elements are null
189       */
190 +    @SuppressWarnings("unchecked")
191      public PriorityQueue(Collection<? extends E> c) {
192 <        initFromCollection(c);
193 <        if (c instanceof SortedSet)
194 <            comparator = (Comparator<? super E>)
195 <                ((SortedSet<? extends E>)c).comparator();
196 <        else if (c instanceof PriorityQueue)
197 <            comparator = (Comparator<? super E>)
198 <                ((PriorityQueue<? extends E>)c).comparator();
192 >        if (c instanceof SortedSet<?>) {
193 >            SortedSet<? extends E> ss = (SortedSet<? extends E>) c;
194 >            this.comparator = (Comparator<? super E>) ss.comparator();
195 >            initElementsFromCollection(ss);
196 >        }
197 >        else if (c instanceof PriorityQueue<?>) {
198 >            PriorityQueue<? extends E> pq = (PriorityQueue<? extends E>) c;
199 >            this.comparator = (Comparator<? super E>) pq.comparator();
200 >            initFromPriorityQueue(pq);
201 >        }
202          else {
203 <            comparator = null;
204 <            heapify();
203 >            this.comparator = null;
204 >            initFromCollection(c);
205          }
206      }
207  
208      /**
209 <     * Creates a <tt>PriorityQueue</tt> containing the elements in the
209 >     * Creates a {@code PriorityQueue} containing the elements in the
210       * specified priority queue.  This priority queue will be
211       * ordered according to the same ordering as the given priority
212       * queue.
213       *
214       * @param  c the priority queue whose elements are to be placed
215       *         into this priority queue
216 <     * @throws ClassCastException if elements of <tt>c</tt> cannot be
217 <     *         compared to one another according to <tt>c</tt>'s
216 >     * @throws ClassCastException if elements of {@code c} cannot be
217 >     *         compared to one another according to {@code c}'s
218       *         ordering
219       * @throws NullPointerException if the specified priority queue or any
220       *         of its elements are null
221       */
222 +    @SuppressWarnings("unchecked")
223      public PriorityQueue(PriorityQueue<? extends E> c) {
224 <        comparator = (Comparator<? super E>)c.comparator();
225 <        initFromCollection(c);
224 >        this.comparator = (Comparator<? super E>) c.comparator();
225 >        initFromPriorityQueue(c);
226      }
227  
228      /**
229 <     * Creates a <tt>PriorityQueue</tt> containing the elements in the
230 <     * specified sorted set.  This priority queue will be ordered
229 >     * Creates a {@code PriorityQueue} containing the elements in the
230 >     * specified sorted set.   This priority queue will be ordered
231       * according to the same ordering as the given sorted set.
232       *
233       * @param  c the sorted set whose elements are to be placed
234 <     *         into this priority queue.
234 >     *         into this priority queue
235       * @throws ClassCastException if elements of the specified sorted
236       *         set cannot be compared to one another according to the
237       *         sorted set's ordering
238       * @throws NullPointerException if the specified sorted set or any
239       *         of its elements are null
240       */
241 +    @SuppressWarnings("unchecked")
242      public PriorityQueue(SortedSet<? extends E> c) {
243 <        comparator = (Comparator<? super E>)c.comparator();
244 <        initFromCollection(c);
243 >        this.comparator = (Comparator<? super E>) c.comparator();
244 >        initElementsFromCollection(c);
245      }
246  
247 <    /**
248 <     * Initialize queue array with elements from the given Collection.
249 <     * @param c the collection
250 <     */
251 <    private void initFromCollection(Collection<? extends E> c) {
247 >    private void initFromPriorityQueue(PriorityQueue<? extends E> c) {
248 >        if (c.getClass() == PriorityQueue.class) {
249 >            this.queue = c.toArray();
250 >            this.size = c.size();
251 >        } else {
252 >            initFromCollection(c);
253 >        }
254 >    }
255 >
256 >    private void initElementsFromCollection(Collection<? extends E> c) {
257          Object[] a = c.toArray();
258          // If c.toArray incorrectly doesn't return Object[], copy it.
259          if (a.getClass() != Object[].class)
260              a = Arrays.copyOf(a, a.length, Object[].class);
261 <        queue = a;
262 <        size = a.length;
261 >        int len = a.length;
262 >        if (len == 1 || this.comparator != null)
263 >            for (Object e : a)
264 >                if (e == null)
265 >                    throw new NullPointerException();
266 >        this.queue = a;
267 >        this.size = a.length;
268 >    }
269 >
270 >    /**
271 >     * Initializes queue array with elements from the given Collection.
272 >     *
273 >     * @param c the collection
274 >     */
275 >    private void initFromCollection(Collection<? extends E> c) {
276 >        initElementsFromCollection(c);
277 >        heapify();
278      }
279  
280      /**
281 +     * The maximum size of array to allocate.
282 +     * Some VMs reserve some header words in an array.
283 +     * Attempts to allocate larger arrays may result in
284 +     * OutOfMemoryError: Requested array size exceeds VM limit
285 +     */
286 +    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
287 +
288 +    /**
289       * Increases the capacity of the array.
290       *
291       * @param minCapacity the desired minimum capacity
292       */
293      private void grow(int minCapacity) {
294 <        if (minCapacity < 0) // overflow
227 <            throw new OutOfMemoryError();
228 <        int oldCapacity = queue.length;
294 >        int oldCapacity = queue.length;
295          // Double size if small; else grow by 50%
296 <        int newCapacity = ((oldCapacity < 64)?
297 <                           ((oldCapacity + 1) * 2):
298 <                           ((oldCapacity / 2) * 3));
299 <        if (newCapacity < 0) // overflow
300 <            newCapacity = Integer.MAX_VALUE;
301 <        if (newCapacity < minCapacity)
236 <            newCapacity = minCapacity;
296 >        int newCapacity = oldCapacity + ((oldCapacity < 64) ?
297 >                                         (oldCapacity + 2) :
298 >                                         (oldCapacity >> 1));
299 >        // overflow-conscious code
300 >        if (newCapacity - MAX_ARRAY_SIZE > 0)
301 >            newCapacity = hugeCapacity(minCapacity);
302          queue = Arrays.copyOf(queue, newCapacity);
303      }
304  
305 +    private static int hugeCapacity(int minCapacity) {
306 +        if (minCapacity < 0) // overflow
307 +            throw new OutOfMemoryError();
308 +        return (minCapacity > MAX_ARRAY_SIZE) ?
309 +            Integer.MAX_VALUE :
310 +            MAX_ARRAY_SIZE;
311 +    }
312 +
313      /**
314       * Inserts the specified element into this priority queue.
315       *
316 <     * @return <tt>true</tt> (as specified by {@link Collection#add})
316 >     * @return {@code true} (as specified by {@link Collection#add})
317       * @throws ClassCastException if the specified element cannot be
318       *         compared with elements currently in this priority queue
319       *         according to the priority queue's ordering
# Line 253 | Line 326 | public class PriorityQueue<E> extends Ab
326      /**
327       * Inserts the specified element into this priority queue.
328       *
329 <     * @return <tt>true</tt> (as specified by {@link Queue#offer})
329 >     * @return {@code true} (as specified by {@link Queue#offer})
330       * @throws ClassCastException if the specified element cannot be
331       *         compared with elements currently in this priority queue
332       *         according to the priority queue's ordering
# Line 266 | Line 339 | public class PriorityQueue<E> extends Ab
339          int i = size;
340          if (i >= queue.length)
341              grow(i + 1);
342 +        siftUp(i, e);
343          size = i + 1;
270        if (i == 0)
271            queue[0] = e;
272        else
273            siftUp(i, e);
344          return true;
345      }
346  
347 +    @SuppressWarnings("unchecked")
348      public E peek() {
349 <        if (size == 0)
279 <            return null;
280 <        return (E) queue[0];
349 >        return (size == 0) ? null : (E) queue[0];
350      }
351  
352      private int indexOf(Object o) {
353 <        if (o != null) {
354 <            for (int i = 0; i < size; i++)
355 <                if (o.equals(queue[i]))
353 >        if (o != null) {
354 >            final Object[] es = queue;
355 >            for (int i = 0, n = size; i < n; i++)
356 >                if (o.equals(es[i]))
357                      return i;
358          }
359          return -1;
# Line 291 | Line 361 | public class PriorityQueue<E> extends Ab
361  
362      /**
363       * Removes a single instance of the specified element from this queue,
364 <     * if it is present.  More formally, removes an element <tt>e</tt> such
365 <     * that <tt>o.equals(e)</tt>, if this queue contains one or more such
366 <     * elements.  Returns true if this queue contained the specified element
367 <     * (or equivalently, if this queue changed as a result of the call).
364 >     * if it is present.  More formally, removes an element {@code e} such
365 >     * that {@code o.equals(e)}, if this queue contains one or more such
366 >     * elements.  Returns {@code true} if and only if this queue contained
367 >     * the specified element (or equivalently, if this queue changed as a
368 >     * result of the call).
369       *
370       * @param o element to be removed from this queue, if present
371 <     * @return <tt>true</tt> if this queue changed as a result of the call
371 >     * @return {@code true} if this queue changed as a result of the call
372       */
373      public boolean remove(Object o) {
374 <        int i = indexOf(o);
375 <        if (i == -1)
376 <            return false;
377 <        else {
378 <            removeAt(i);
379 <            return true;
380 <        }
374 >        int i = indexOf(o);
375 >        if (i == -1)
376 >            return false;
377 >        else {
378 >            removeAt(i);
379 >            return true;
380 >        }
381      }
382  
383      /**
384 <     * Version of remove using reference equality, not equals.
314 <     * Needed by iterator.remove.
384 >     * Identity-based version for use in Itr.remove.
385       *
386       * @param o element to be removed from this queue, if present
317     * @return <tt>true</tt> if removed
387       */
388 <    boolean removeEq(Object o) {
389 <        for (int i = 0; i < size; i++) {
390 <            if (o == queue[i]) {
388 >    void removeEq(Object o) {
389 >        final Object[] es = queue;
390 >        for (int i = 0, n = size; i < n; i++) {
391 >            if (o == es[i]) {
392                  removeAt(i);
393 <                return true;
393 >                break;
394              }
395          }
326        return false;
396      }
397  
398      /**
399 <     * Returns <tt>true</tt> if this queue contains the specified element.
400 <     * More formally, returns <tt>true</tt> if and only if this queue contains
401 <     * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
399 >     * Returns {@code true} if this queue contains the specified element.
400 >     * More formally, returns {@code true} if and only if this queue contains
401 >     * at least one element {@code e} such that {@code o.equals(e)}.
402       *
403       * @param o object to be checked for containment in this queue
404 <     * @return <tt>true</tt> if this queue contains the specified element
404 >     * @return {@code true} if this queue contains the specified element
405       */
406      public boolean contains(Object o) {
407 <        return indexOf(o) != -1;
407 >        return indexOf(o) >= 0;
408      }
409  
410      /**
411 <     * Returns an array containing all of the elements in this queue,
411 >     * Returns an array containing all of the elements in this queue.
412       * The elements are in no particular order.
413       *
414       * <p>The returned array will be "safe" in that no references to it are
415 <     * maintained by this list.  (In other words, this method must allocate
415 >     * maintained by this queue.  (In other words, this method must allocate
416       * a new array).  The caller is thus free to modify the returned array.
417       *
418 +     * <p>This method acts as bridge between array-based and collection-based
419 +     * APIs.
420 +     *
421       * @return an array containing all of the elements in this queue
422       */
423      public Object[] toArray() {
# Line 353 | Line 425 | public class PriorityQueue<E> extends Ab
425      }
426  
427      /**
428 <     * Returns an array containing all of the elements in this queue.
429 <     * The elements are in no particular order.  The runtime type of
430 <     * the returned array is that of the specified array.  If the queue
431 <     * fits in the specified array, it is returned therein.
432 <     * Otherwise, a new array is allocated with the runtime type of
433 <     * the specified array and the size of this queue.
428 >     * Returns an array containing all of the elements in this queue; the
429 >     * runtime type of the returned array is that of the specified array.
430 >     * The returned array elements are in no particular order.
431 >     * If the queue fits in the specified array, it is returned therein.
432 >     * Otherwise, a new array is allocated with the runtime type of the
433 >     * specified array and the size of this queue.
434       *
435       * <p>If the queue fits in the specified array with room to spare
436       * (i.e., the array has more elements than the queue), the element in
437       * the array immediately following the end of the collection is set to
438 <     * <tt>null</tt>.  (This is useful in determining the length of the
439 <     * queue <i>only</i> if the caller knows that the queue does not contain
440 <     * any null elements.)
438 >     * {@code null}.
439 >     *
440 >     * <p>Like the {@link #toArray()} method, this method acts as bridge between
441 >     * array-based and collection-based APIs.  Further, this method allows
442 >     * precise control over the runtime type of the output array, and may,
443 >     * under certain circumstances, be used to save allocation costs.
444 >     *
445 >     * <p>Suppose {@code x} is a queue known to contain only strings.
446 >     * The following code can be used to dump the queue into a newly
447 >     * allocated array of {@code String}:
448 >     *
449 >     * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
450 >     *
451 >     * Note that {@code toArray(new Object[0])} is identical in function to
452 >     * {@code toArray()}.
453       *
454       * @param a the array into which the elements of the queue are to
455       *          be stored, if it is big enough; otherwise, a new array of the
456       *          same runtime type is allocated for this purpose.
457 <     * @return an array containing the elements of the queue
457 >     * @return an array containing all of the elements in this queue
458       * @throws ArrayStoreException if the runtime type of the specified array
459       *         is not a supertype of the runtime type of every element in
460       *         this queue
461       * @throws NullPointerException if the specified array is null
462       */
463 +    @SuppressWarnings("unchecked")
464      public <T> T[] toArray(T[] a) {
465 +        final int size = this.size;
466          if (a.length < size)
467              // Make a new array of a's runtime type, but my contents:
468              return (T[]) Arrays.copyOf(queue, size, a.getClass());
469 <        System.arraycopy(queue, 0, a, 0, size);
469 >        System.arraycopy(queue, 0, a, 0, size);
470          if (a.length > size)
471              a[size] = null;
472          return a;
# Line 401 | Line 487 | public class PriorityQueue<E> extends Ab
487           * Index (into queue array) of element to be returned by
488           * subsequent call to next.
489           */
490 <        private int cursor = 0;
490 >        private int cursor;
491  
492          /**
493           * Index of element returned by most recent call to next,
# Line 419 | Line 505 | public class PriorityQueue<E> extends Ab
505           * after we've completed the "normal" iteration.
506           *
507           * We expect that most iterations, even those involving removals,
508 <         * will not use need to store elements in this field.
508 >         * will not need to store elements in this field.
509           */
510 <        private ArrayDeque<E> forgetMeNot = null;
510 >        private ArrayDeque<E> forgetMeNot;
511  
512          /**
513           * Element returned by the most recent call to next iff that
514           * element was drawn from the forgetMeNot list.
515           */
516 <        private E lastRetElt = null;
516 >        private E lastRetElt;
517  
518          /**
519           * The modCount value that the iterator believes that the backing
520 <         * List should have.  If this expectation is violated, the iterator
520 >         * Queue should have.  If this expectation is violated, the iterator
521           * has detected concurrent modification.
522           */
523          private int expectedModCount = modCount;
524  
525 +        Itr() {}                        // prevent access constructor creation
526 +
527          public boolean hasNext() {
528              return cursor < size ||
529                  (forgetMeNot != null && !forgetMeNot.isEmpty());
530          }
531  
532 +        @SuppressWarnings("unchecked")
533          public E next() {
534              if (expectedModCount != modCount)
535                  throw new ConcurrentModificationException();
# Line 458 | Line 547 | public class PriorityQueue<E> extends Ab
547          public void remove() {
548              if (expectedModCount != modCount)
549                  throw new ConcurrentModificationException();
461            if (lastRet == -1 && lastRetElt == null)
462                throw new IllegalStateException();
550              if (lastRet != -1) {
551                  E moved = PriorityQueue.this.removeAt(lastRet);
552                  lastRet = -1;
# Line 467 | Line 554 | public class PriorityQueue<E> extends Ab
554                      cursor--;
555                  else {
556                      if (forgetMeNot == null)
557 <                        forgetMeNot = new ArrayDeque<E>();
557 >                        forgetMeNot = new ArrayDeque<>();
558                      forgetMeNot.add(moved);
559                  }
560 <            } else {
560 >            } else if (lastRetElt != null) {
561                  PriorityQueue.this.removeEq(lastRetElt);
562                  lastRetElt = null;
563 +            } else {
564 +                throw new IllegalStateException();
565              }
566              expectedModCount = modCount;
567          }
479
568      }
569  
570      public int size() {
# Line 489 | Line 577 | public class PriorityQueue<E> extends Ab
577       */
578      public void clear() {
579          modCount++;
580 <        for (int i = 0; i < size; i++)
581 <            queue[i] = null;
580 >        final Object[] es = queue;
581 >        for (int i = 0, n = size; i < n; i++)
582 >            es[i] = null;
583          size = 0;
584      }
585  
586 +    @SuppressWarnings("unchecked")
587      public E poll() {
588          if (size == 0)
589              return null;
590          int s = --size;
591          modCount++;
592 <        E result = (E)queue[0];
593 <        E x = (E)queue[s];
592 >        E result = (E) queue[0];
593 >        E x = (E) queue[s];
594          queue[s] = null;
595          if (s != 0)
596              siftDown(0, x);
# Line 517 | Line 607 | public class PriorityQueue<E> extends Ab
607       * i.  Under these circumstances, this method returns the element
608       * that was previously at the end of the list and is now at some
609       * position before i. This fact is used by iterator.remove so as to
610 <     * avoid missing traverseing elements.
610 >     * avoid missing traversing elements.
611       */
612 <    private E removeAt(int i) {
613 <        assert i >= 0 && i < size;
612 >    @SuppressWarnings("unchecked")
613 >    E removeAt(int i) {
614 >        // assert i >= 0 && i < size;
615          modCount++;
616          int s = --size;
617          if (s == i) // removed last element
# Line 543 | Line 634 | public class PriorityQueue<E> extends Ab
634       * promoting x up the tree until it is greater than or equal to
635       * its parent, or is the root.
636       *
637 <     * To simplify and speed up coercions and comparisons. the
637 >     * To simplify and speed up coercions and comparisons, the
638       * Comparable and Comparator versions are separated into different
639       * methods that are otherwise identical. (Similarly for siftDown.)
640       *
# Line 557 | Line 648 | public class PriorityQueue<E> extends Ab
648              siftUpComparable(k, x);
649      }
650  
651 +    @SuppressWarnings("unchecked")
652      private void siftUpComparable(int k, E x) {
653          Comparable<? super E> key = (Comparable<? super E>) x;
654          while (k > 0) {
655              int parent = (k - 1) >>> 1;
656              Object e = queue[parent];
657 <            if (key.compareTo((E)e) >= 0)
657 >            if (key.compareTo((E) e) >= 0)
658                  break;
659              queue[k] = e;
660              k = parent;
# Line 570 | Line 662 | public class PriorityQueue<E> extends Ab
662          queue[k] = key;
663      }
664  
665 +    @SuppressWarnings("unchecked")
666      private void siftUpUsingComparator(int k, E x) {
667          while (k > 0) {
668              int parent = (k - 1) >>> 1;
669              Object e = queue[parent];
670 <            if (comparator.compare(x, (E)e) >= 0)
670 >            if (comparator.compare(x, (E) e) >= 0)
671                  break;
672              queue[k] = e;
673              k = parent;
# Line 597 | Line 690 | public class PriorityQueue<E> extends Ab
690              siftDownComparable(k, x);
691      }
692  
693 +    @SuppressWarnings("unchecked")
694      private void siftDownComparable(int k, E x) {
695          Comparable<? super E> key = (Comparable<? super E>)x;
696          int half = size >>> 1;        // loop while a non-leaf
# Line 605 | Line 699 | public class PriorityQueue<E> extends Ab
699              Object c = queue[child];
700              int right = child + 1;
701              if (right < size &&
702 <                ((Comparable<? super E>)c).compareTo((E)queue[right]) > 0)
702 >                ((Comparable<? super E>) c).compareTo((E) queue[right]) > 0)
703                  c = queue[child = right];
704 <            if (key.compareTo((E)c) <= 0)
704 >            if (key.compareTo((E) c) <= 0)
705                  break;
706              queue[k] = c;
707              k = child;
# Line 615 | Line 709 | public class PriorityQueue<E> extends Ab
709          queue[k] = key;
710      }
711  
712 +    @SuppressWarnings("unchecked")
713      private void siftDownUsingComparator(int k, E x) {
714          int half = size >>> 1;
715          while (k < half) {
# Line 622 | Line 717 | public class PriorityQueue<E> extends Ab
717              Object c = queue[child];
718              int right = child + 1;
719              if (right < size &&
720 <                comparator.compare((E)c, (E)queue[right]) > 0)
720 >                comparator.compare((E) c, (E) queue[right]) > 0)
721                  c = queue[child = right];
722 <            if (comparator.compare(x, (E)c) <= 0)
722 >            if (comparator.compare(x, (E) c) <= 0)
723                  break;
724              queue[k] = c;
725              k = child;
# Line 635 | Line 730 | public class PriorityQueue<E> extends Ab
730      /**
731       * Establishes the heap invariant (described above) in the entire tree,
732       * assuming nothing about the order of the elements prior to the call.
733 +     * This classic algorithm due to Floyd (1964) is known to be O(size).
734       */
735 +    @SuppressWarnings("unchecked")
736      private void heapify() {
737 <        for (int i = (size >>> 1) - 1; i >= 0; i--)
738 <            siftDown(i, (E)queue[i]);
737 >        final Object[] es = queue;
738 >        int i = (size >>> 1) - 1;
739 >        if (comparator == null)
740 >            for (; i >= 0; i--)
741 >                siftDownComparable(i, (E) es[i]);
742 >        else
743 >            for (; i >= 0; i--)
744 >                siftDownUsingComparator(i, (E) es[i]);
745      }
746  
747      /**
748       * Returns the comparator used to order the elements in this
749 <     * queue, or <tt>null</tt> if this queue is sorted according to
749 >     * queue, or {@code null} if this queue is sorted according to
750       * the {@linkplain Comparable natural ordering} of its elements.
751       *
752       * @return the comparator used to order this queue, or
753 <     *         <tt>null</tt> if this queue is sorted according to the
754 <     *         natural ordering of its elements.
753 >     *         {@code null} if this queue is sorted according to the
754 >     *         natural ordering of its elements
755       */
756      public Comparator<? super E> comparator() {
757          return comparator;
758      }
759  
760      /**
761 <     * Save the state of the instance to a stream (that
659 <     * is, serialize it).
761 >     * Saves this queue to a stream (that is, serializes it).
762       *
661     * @serialData The length of the array backing the instance is
662     * emitted (int), followed by all of its elements (each an
663     * <tt>Object</tt>) in the proper order.
763       * @param s the stream
764 +     * @throws java.io.IOException if an I/O error occurs
765 +     * @serialData The length of the array backing the instance is
766 +     *             emitted (int), followed by all of its elements
767 +     *             (each an {@code Object}) in the proper order.
768       */
769      private void writeObject(java.io.ObjectOutputStream s)
770 <        throws java.io.IOException{
770 >        throws java.io.IOException {
771          // Write out element count, and any hidden stuff
772          s.defaultWriteObject();
773  
774 <        // Write out array length
775 <        // For compatibility with 1.5 version, must be at least 2.
673 <        s.writeInt(Math.max(2, queue.length));
774 >        // Write out array length, for compatibility with 1.5 version
775 >        s.writeInt(Math.max(2, size + 1));
776  
777 <        // Write out all elements in the proper order.
778 <        for (int i=0; i<size; i++)
779 <            s.writeObject(queue[i]);
777 >        // Write out all elements in the "proper order".
778 >        final Object[] es = queue;
779 >        for (int i = 0, n = size; i < n; i++)
780 >            s.writeObject(es[i]);
781      }
782  
783      /**
784 <     * Reconstitute the <tt>PriorityQueue</tt> instance from a stream
785 <     * (that is, deserialize it).
784 >     * Reconstitutes the {@code PriorityQueue} instance from a stream
785 >     * (that is, deserializes it).
786 >     *
787       * @param s the stream
788 +     * @throws ClassNotFoundException if the class of a serialized object
789 +     *         could not be found
790 +     * @throws java.io.IOException if an I/O error occurs
791       */
792      private void readObject(java.io.ObjectInputStream s)
793          throws java.io.IOException, ClassNotFoundException {
794          // Read in size, and any hidden stuff
795          s.defaultReadObject();
796  
797 <        // Read in array length and allocate array
798 <        int arrayLength = s.readInt();
799 <        queue = new Object[arrayLength];
800 <
801 <        // Read in all elements in the proper order.
802 <        for (int i=0; i<size; i++)
803 <            queue[i] = (E) s.readObject();
797 >        // Read in (and discard) array length
798 >        s.readInt();
799 >
800 >        SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, size);
801 >        queue = new Object[size];
802 >
803 >        // Read in all elements.
804 >        final Object[] es = queue;
805 >        for (int i = 0, n = size; i < n; i++)
806 >            es[i] = s.readObject();
807 >
808 >        // Elements are guaranteed to be in "proper order", but the
809 >        // spec has never explained what that might be.
810 >        heapify();
811 >    }
812 >
813 >    /**
814 >     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
815 >     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
816 >     * queue. The spliterator does not traverse elements in any particular order
817 >     * (the {@link Spliterator#ORDERED ORDERED} characteristic is not reported).
818 >     *
819 >     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
820 >     * {@link Spliterator#SUBSIZED}, and {@link Spliterator#NONNULL}.
821 >     * Overriding implementations should document the reporting of additional
822 >     * characteristic values.
823 >     *
824 >     * @return a {@code Spliterator} over the elements in this queue
825 >     * @since 1.8
826 >     */
827 >    public final Spliterator<E> spliterator() {
828 >        return new PriorityQueueSpliterator(0, -1, 0);
829 >    }
830 >
831 >    final class PriorityQueueSpliterator implements Spliterator<E> {
832 >        private int index;            // current index, modified on advance/split
833 >        private int fence;            // -1 until first use
834 >        private int expectedModCount; // initialized when fence set
835 >
836 >        /** Creates new spliterator covering the given range. */
837 >        PriorityQueueSpliterator(int origin, int fence, int expectedModCount) {
838 >            this.index = origin;
839 >            this.fence = fence;
840 >            this.expectedModCount = expectedModCount;
841 >        }
842 >
843 >        private int getFence() { // initialize fence to size on first use
844 >            int hi;
845 >            if ((hi = fence) < 0) {
846 >                expectedModCount = modCount;
847 >                hi = fence = size;
848 >            }
849 >            return hi;
850 >        }
851 >
852 >        public PriorityQueueSpliterator trySplit() {
853 >            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
854 >            return (lo >= mid) ? null :
855 >                new PriorityQueueSpliterator(lo, index = mid, expectedModCount);
856 >        }
857 >
858 >        @SuppressWarnings("unchecked")
859 >        public void forEachRemaining(Consumer<? super E> action) {
860 >            if (action == null)
861 >                throw new NullPointerException();
862 >            if (fence < 0) { fence = size; expectedModCount = modCount; }
863 >            final Object[] a = queue;
864 >            int i, hi; E e;
865 >            for (i = index, index = hi = fence; i < hi; i++) {
866 >                if ((e = (E) a[i]) == null)
867 >                    break;      // must be CME
868 >                action.accept(e);
869 >            }
870 >            if (modCount != expectedModCount)
871 >                throw new ConcurrentModificationException();
872 >        }
873 >
874 >        @SuppressWarnings("unchecked")
875 >        public boolean tryAdvance(Consumer<? super E> action) {
876 >            if (action == null)
877 >                throw new NullPointerException();
878 >            if (fence < 0) { fence = size; expectedModCount = modCount; }
879 >            int i;
880 >            if ((i = index) < fence) {
881 >                index = i + 1;
882 >                E e;
883 >                if ((e = (E) queue[i]) == null
884 >                    || modCount != expectedModCount)
885 >                    throw new ConcurrentModificationException();
886 >                action.accept(e);
887 >                return true;
888 >            }
889 >            return false;
890 >        }
891 >
892 >        public long estimateSize() {
893 >            return getFence() - index;
894 >        }
895 >
896 >        public int characteristics() {
897 >            return Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.NONNULL;
898 >        }
899      }
900  
901 +    /**
902 +     * @throws NullPointerException {@inheritDoc}
903 +     */
904 +    @SuppressWarnings("unchecked")
905 +    public void forEach(Consumer<? super E> action) {
906 +        Objects.requireNonNull(action);
907 +        final int expectedModCount = modCount;
908 +        final Object[] es = queue;
909 +        for (int i = 0, n = size; i < n; i++)
910 +            action.accept((E) es[i]);
911 +        if (expectedModCount != modCount)
912 +            throw new ConcurrentModificationException();
913 +    }
914   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines