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.40 by dl, Fri Sep 12 15:38:26 2003 UTC vs.
Revision 1.122 by jsr166, Sun May 6 02:08:36 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 2003 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  
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 heap.
33 < * This queue orders elements according to an order specified at construction
34 < * time, which is specified in the same manner as {@link java.util.TreeSet}
35 < * and {@link java.util.TreeMap}: elements are ordered either according to
36 < * their <i>natural order</i> (see {@link Comparable}), or according to a
37 < * {@link java.util.Comparator}, depending on which constructor is used.
38 < *
39 < * <p>The <em>head</em> of this queue is the <em>least</em> element with
19 < * respect to the specified ordering.  If multiple elements are tied for least
20 < * value, the head is one of those elements. A priority queue does not permit
21 < * <tt>null</tt> elements.
22 < *
23 < * <p>The {@link #remove()} and {@link #poll()} methods remove and
24 < * return the head of the queue.
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 {@link #element()} and {@link #peek()} methods return, but do
42 < * not delete, the head of the queue.
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 {@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 a <i>capacity</i>.  The
49 < * capacity is the size of the array used internally to store the
48 > * <p>A priority queue is unbounded, but has an internal
49 > * <i>capacity</i> governing the size of an array used to store the
50   * elements on the queue.  It is always at least as large as the queue
51   * size.  As elements are added to a priority queue, its capacity
52   * grows automatically.  The details of the growth policy are not
53   * specified.
54   *
55 < * <p>The Iterator provided in method {@link #iterator()} is <em>not</em>
56 < * guaranteed to traverse the elements of the PriorityQueue in any
57 < * particular order. If you need ordered traversal, consider using
58 < * <tt>Arrays.sort(pq.toArray())</tt>.
59 < *
60 < * <p> <strong>Note that this implementation is not synchronized.</strong>
61 < * Multiple threads should not access a <tt>PriorityQueue</tt>
62 < * instance concurrently if any of the threads modifies the list
63 < * structurally. Instead, use the thread-safe {@link
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()} 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 {@code Arrays.sort(pq.toArray())}.
62 > *
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 < *
70 < * <p>Implementation note: this implementation provides O(log(n)) time
71 < * for the insertion methods (<tt>offer</tt>, <tt>poll</tt>,
72 < * <tt>remove()</tt> and <tt>add</tt>) methods; linear time for the
73 < * <tt>remove(Object)</tt> and <tt>contains(Object)</tt> methods; and
74 < * constant time for the retrieval methods (<tt>peek</tt>,
53 < * <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 %I%, %G%
82 < * @author Josh Bloch
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 Queue<E>, java.io.Serializable {
85 >    implements java.io.Serializable {
86  
87      private static final long serialVersionUID = -7720805057305804111L;
88  
89      private static final int DEFAULT_INITIAL_CAPACITY = 11;
90  
91      /**
92 <     * Priority queue represented as a balanced binary heap: the two children
93 <     * of queue[n] are queue[2*n] and queue[2*n + 1].  The priority queue is
94 <     * ordered by comparator, or by the elements' natural ordering, if
95 <     * comparator is null:  For each node n in the heap and each descendant d
96 <     * of n, n <= d.
97 <     *
76 <     * The element with the lowest value is in queue[1], assuming the queue is
77 <     * nonempty.  (A one-based array is used in preference to the traditional
78 <     * zero-based array to simplify parent and child calculations.)
79 <     *
80 <     * queue.length must be >= 2, even if size == 0.
92 >     * Priority queue represented as a balanced binary heap: the two
93 >     * children of queue[n] are queue[2*n+1] and queue[2*(n+1)].  The
94 >     * priority queue is ordered by comparator, or by the elements'
95 >     * natural ordering, if comparator is null: For each node n in the
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 96 | 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 capacity
120 <     * (11) that orders its elements according to their natural
121 <     * ordering (using <tt>Comparable</tt>).
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       */
123      public PriorityQueue() {
124          this(DEFAULT_INITIAL_CAPACITY, null);
125      }
126  
127      /**
128 <     * Creates a <tt>PriorityQueue</tt> with the specified initial capacity
129 <     * that orders its elements according to their natural ordering
130 <     * (using <tt>Comparable</tt>).
131 <     *
132 <     * @param initialCapacity the initial capacity for this priority queue.
133 <     * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
134 <     * than 1
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 {@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 used to order this priority queue.
159 <     * If <tt>null</tt> then the order depends on the elements' natural
160 <     * ordering.
161 <     * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
162 <     * than 1
157 >     * @param  initialCapacity the initial capacity for this priority queue
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,
164 >    public PriorityQueue(int initialCapacity,
165                           Comparator<? super E> comparator) {
166 +        // Note: This restriction of at least one is not actually needed,
167 +        // but continues for 1.5 compatibility
168          if (initialCapacity < 1)
169              throw new IllegalArgumentException();
170 <        this.queue = new Object[initialCapacity + 1];
170 >        this.queue = new Object[initialCapacity];
171          this.comparator = comparator;
172      }
173  
174      /**
175 <     * Common code to initialize underlying queue array across
176 <     * constructors below.
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
184 >     * @throws ClassCastException if elements of the specified collection
185 >     *         cannot be compared to one another according to the priority
186 >     *         queue's ordering
187 >     * @throws NullPointerException if the specified collection or any
188 >     *         of its elements are null
189       */
190 <    private void initializeArray(Collection<? extends E> c) {
191 <        int sz = c.size();
192 <        int initialCapacity = (int)Math.min((sz * 110L) / 100,
193 <                                            Integer.MAX_VALUE - 1);
194 <        if (initialCapacity < 1)
195 <            initialCapacity = 1;
196 <
197 <        this.queue = new Object[initialCapacity + 1];
190 >    @SuppressWarnings("unchecked")
191 >    public PriorityQueue(Collection<? extends E> c) {
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 >            this.comparator = null;
204 >            initFromCollection(c);
205 >        }
206      }
207  
208      /**
209 <     * Initially fill elements of the queue array under the
210 <     * knowledge that it is sorted or is another PQ, in which
211 <     * case we can just place the elements in the order presented.
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 {@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 <    private void fillFromSorted(Collection<? extends E> c) {
223 <        for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
224 <            queue[++size] = i.next();
222 >    @SuppressWarnings("unchecked")
223 >    public PriorityQueue(PriorityQueue<? extends E> c) {
224 >        this.comparator = (Comparator<? super E>) c.comparator();
225 >        initFromPriorityQueue(c);
226      }
227  
228      /**
229 <     * Initially fill elements of the queue array that is not to our knowledge
230 <     * sorted, so we must rearrange the elements to guarantee the heap
231 <     * invariant.
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
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 <    private void fillFromUnsorted(Collection<? extends E> c) {
242 <        for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
243 <            queue[++size] = i.next();
244 <        heapify();
241 >    @SuppressWarnings("unchecked")
242 >    public PriorityQueue(SortedSet<? extends E> c) {
243 >        this.comparator = (Comparator<? super E>) c.comparator();
244 >        initElementsFromCollection(c);
245      }
246  
247 <    /**
248 <     * Creates a <tt>PriorityQueue</tt> containing the elements in the
249 <     * specified collection.  The priority queue has an initial
250 <     * capacity of 110% of the size of the specified collection or 1
181 <     * if the collection is empty.  If the specified collection is an
182 <     * instance of a {@link java.util.SortedSet} or is another
183 <     * <tt>PriorityQueue</tt>, the priority queue will be sorted
184 <     * according to the same comparator, or according to its elements'
185 <     * natural order if the collection is sorted according to its
186 <     * elements' natural order.  Otherwise, the priority queue is
187 <     * ordered according to its elements' natural order.
188 <     *
189 <     * @param c the collection whose elements are to be placed
190 <     *        into this priority queue.
191 <     * @throws ClassCastException if elements of the specified collection
192 <     *         cannot be compared to one another according to the priority
193 <     *         queue's ordering.
194 <     * @throws NullPointerException if <tt>c</tt> or any element within it
195 <     * is <tt>null</tt>
196 <     */
197 <    public PriorityQueue(Collection<? extends E> c) {
198 <        initializeArray(c);
199 <        if (c instanceof SortedSet) {
200 <            // @fixme double-cast workaround for compiler
201 <            SortedSet<? extends E> s = (SortedSet<? extends E>) (SortedSet)c;
202 <            comparator = (Comparator<? super E>)s.comparator();
203 <            fillFromSorted(s);
204 <        } else if (c instanceof PriorityQueue) {
205 <            PriorityQueue<? extends E> s = (PriorityQueue<? extends E>) c;
206 <            comparator = (Comparator<? super E>)s.comparator();
207 <            fillFromSorted(s);
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 <            comparator = null;
210 <            fillFromUnsorted(c);
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 +        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 <     * Creates a <tt>PriorityQueue</tt> containing the elements in the
216 <     * specified collection.  The priority queue has an initial
217 <     * capacity of 110% of the size of the specified collection or 1
218 <     * if the collection is empty.  This priority queue will be sorted
219 <     * according to the same comparator as the given collection, or
220 <     * according to its elements' natural order if the collection is
221 <     * sorted according to its elements' natural order.
271 >     * Initializes queue array with elements from the given Collection.
272       *
273 <     * @param c the collection whose elements are to be placed
224 <     *        into this priority queue.
225 <     * @throws ClassCastException if elements of the specified collection
226 <     *         cannot be compared to one another according to the priority
227 <     *         queue's ordering.
228 <     * @throws NullPointerException if <tt>c</tt> or any element within it
229 <     * is <tt>null</tt>
273 >     * @param c the collection
274       */
275 <    public PriorityQueue(PriorityQueue<? extends E> c) {
276 <        initializeArray(c);
277 <        comparator = (Comparator<? super E>)c.comparator();
234 <        fillFromSorted(c);
275 >    private void initFromCollection(Collection<? extends E> c) {
276 >        initElementsFromCollection(c);
277 >        heapify();
278      }
279  
280      /**
281 <     * Creates a <tt>PriorityQueue</tt> containing the elements in the
282 <     * specified collection.  The priority queue has an initial
283 <     * capacity of 110% of the size of the specified collection or 1
284 <     * if the collection is empty.  This priority queue will be sorted
285 <     * according to the same comparator as the given collection, or
286 <     * according to its elements' natural order if the collection is
287 <     * sorted according to its elements' natural order.
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 c the collection whose elements are to be placed
247 <     *        into this priority queue.
248 <     * @throws ClassCastException if elements of the specified collection
249 <     *         cannot be compared to one another according to the priority
250 <     *         queue's ordering.
251 <     * @throws NullPointerException if <tt>c</tt> or any element within it
252 <     * is <tt>null</tt>
291 >     * @param minCapacity the desired minimum capacity
292       */
293 <    public PriorityQueue(SortedSet<? extends E> c) {
294 <        initializeArray(c);
295 <        comparator = (Comparator<? super E>)c.comparator();
296 <        fillFromSorted(c);
293 >    private void grow(int minCapacity) {
294 >        int oldCapacity = queue.length;
295 >        // Double size if small; else grow by 50%
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 <     * Resize array, if necessary, to be able to hold given index
314 >     * Inserts the specified element into this priority queue.
315 >     *
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
320 >     * @throws NullPointerException if the specified element is null
321       */
322 <    private void grow(int index) {
323 <        int newlen = queue.length;
265 <        if (index < newlen) // don't need to grow
266 <            return;
267 <        if (index == Integer.MAX_VALUE)
268 <            throw new OutOfMemoryError();
269 <        while (newlen <= index) {
270 <            if (newlen >= Integer.MAX_VALUE / 2)  // avoid overflow
271 <                newlen = Integer.MAX_VALUE;
272 <            else
273 <                newlen <<= 2;
274 <        }
275 <        Object[] newQueue = new Object[newlen];
276 <        System.arraycopy(queue, 0, newQueue, 0, queue.length);
277 <        queue = newQueue;
322 >    public boolean add(E e) {
323 >        return offer(e);
324      }
279            
325  
326      /**
327 <     * Inserts the specified element to this priority queue.
327 >     * Inserts the specified element into this priority queue.
328       *
329 <     * @return <tt>true</tt>
330 <     * @throws ClassCastException if the specified element cannot be compared
331 <     * with elements currently in the priority queue according
332 <     * to the priority queue's ordering.
333 <     * @throws NullPointerException if the specified element is <tt>null</tt>.
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
333 >     * @throws NullPointerException if the specified element is null
334       */
335 <    public boolean offer(E o) {
336 <        if (o == null)
335 >    public boolean offer(E e) {
336 >        if (e == null)
337              throw new NullPointerException();
338          modCount++;
339 <        ++size;
340 <
341 <        // Grow backing store if necessary
342 <        if (size >= queue.length)
343 <            grow(size);
299 <
300 <        queue[size] = o;
301 <        fixUp(size);
339 >        int i = size;
340 >        if (i >= queue.length)
341 >            grow(i + 1);
342 >        siftUp(i, e);
343 >        size = i + 1;
344          return true;
345      }
346  
347 +    @SuppressWarnings("unchecked")
348      public E peek() {
349 <        if (size == 0)
307 <            return null;
308 <        return (E) queue[1];
349 >        return (size == 0) ? null : (E) queue[0];
350      }
351  
352 <    // Collection Methods - the first two override to update docs
352 >    private int indexOf(Object o) {
353 >        if (o != null) {
354 >            for (int i = 0; i < size; i++)
355 >                if (o.equals(queue[i]))
356 >                    return i;
357 >        }
358 >        return -1;
359 >    }
360  
361      /**
362 <     * Adds the specified element to this queue.
363 <     * @return <tt>true</tt> (as per the general contract of
364 <     * <tt>Collection.add</tt>).
365 <     *
366 <     * @throws NullPointerException if the specified element is <tt>null</tt>.
367 <     * @throws ClassCastException if the specified element cannot be compared
368 <     * with elements currently in the priority queue according
369 <     * to the priority queue's ordering.
370 <     */
323 <    public boolean add(E o) {
324 <        return super.add(o);
325 <    }
326 <
327 <  
328 <    /**
329 <     * Adds all of the elements in the specified collection to this queue.
330 <     * The behavior of this operation is undefined if
331 <     * the specified collection is modified while the operation is in
332 <     * progress.  (This implies that the behavior of this call is undefined if
333 <     * the specified collection is this queue, and this queue is nonempty.)
334 <     * <p>
335 <     * This implementation iterates over the specified collection, and adds
336 <     * each object returned by the iterator to this collection, in turn.
337 <     * @param c collection whose elements are to be added to this queue
338 <     * @return <tt>true</tt> if this queue changed as a result of the
339 <     *         call.
340 <     * @throws NullPointerException if <tt>c</tt> or any element in <tt>c</tt>
341 <     * is <tt>null</tt>
342 <     * @throws ClassCastException if any element cannot be compared
343 <     * with elements currently in the priority queue according
344 <     * to the priority queue's ordering.
362 >     * Removes a single instance of the specified element from this queue,
363 >     * if it is present.  More formally, removes an element {@code e} such
364 >     * that {@code o.equals(e)}, if this queue contains one or more such
365 >     * elements.  Returns {@code true} if and only if this queue contained
366 >     * the specified element (or equivalently, if this queue changed as a
367 >     * result of the call).
368 >     *
369 >     * @param o element to be removed from this queue, if present
370 >     * @return {@code true} if this queue changed as a result of the call
371       */
346    public boolean addAll(Collection<? extends E> c) {
347        return super.addAll(c);
348    }
349
372      public boolean remove(Object o) {
373 <        if (o == null)
373 >        int i = indexOf(o);
374 >        if (i == -1)
375              return false;
376 +        else {
377 +            removeAt(i);
378 +            return true;
379 +        }
380 +    }
381  
382 <        if (comparator == null) {
383 <            for (int i = 1; i <= size; i++) {
384 <                if (((Comparable<E>)queue[i]).compareTo((E)o) == 0) {
385 <                    removeAt(i);
386 <                    return true;
387 <                }
388 <            }
389 <        } else {
390 <            for (int i = 1; i <= size; i++) {
391 <                if (comparator.compare((E)queue[i], (E)o) == 0) {
392 <                    removeAt(i);
393 <                    return true;
366 <                }
382 >    /**
383 >     * Version of remove using reference equality, not equals.
384 >     * Needed by iterator.remove.
385 >     *
386 >     * @param o element to be removed from this queue, if present
387 >     * @return {@code true} if removed
388 >     */
389 >    boolean removeEq(Object o) {
390 >        for (int i = 0; i < size; i++) {
391 >            if (o == queue[i]) {
392 >                removeAt(i);
393 >                return true;
394              }
395          }
396          return false;
397      }
398  
399      /**
400 +     * Returns {@code true} if this queue contains the specified element.
401 +     * More formally, returns {@code true} if and only if this queue contains
402 +     * at least one element {@code e} such that {@code o.equals(e)}.
403 +     *
404 +     * @param o object to be checked for containment in this queue
405 +     * @return {@code true} if this queue contains the specified element
406 +     */
407 +    public boolean contains(Object o) {
408 +        return indexOf(o) >= 0;
409 +    }
410 +
411 +    /**
412 +     * Returns an array containing all of the elements in this queue.
413 +     * The elements are in no particular order.
414 +     *
415 +     * <p>The returned array will be "safe" in that no references to it are
416 +     * maintained by this queue.  (In other words, this method must allocate
417 +     * a new array).  The caller is thus free to modify the returned array.
418 +     *
419 +     * <p>This method acts as bridge between array-based and collection-based
420 +     * APIs.
421 +     *
422 +     * @return an array containing all of the elements in this queue
423 +     */
424 +    public Object[] toArray() {
425 +        return Arrays.copyOf(queue, size);
426 +    }
427 +
428 +    /**
429 +     * Returns an array containing all of the elements in this queue; the
430 +     * runtime type of the returned array is that of the specified array.
431 +     * The returned array elements are in no particular order.
432 +     * If the queue fits in the specified array, it is returned therein.
433 +     * Otherwise, a new array is allocated with the runtime type of the
434 +     * specified array and the size of this queue.
435 +     *
436 +     * <p>If the queue fits in the specified array with room to spare
437 +     * (i.e., the array has more elements than the queue), the element in
438 +     * the array immediately following the end of the collection is set to
439 +     * {@code null}.
440 +     *
441 +     * <p>Like the {@link #toArray()} method, this method acts as bridge between
442 +     * array-based and collection-based APIs.  Further, this method allows
443 +     * precise control over the runtime type of the output array, and may,
444 +     * under certain circumstances, be used to save allocation costs.
445 +     *
446 +     * <p>Suppose {@code x} is a queue known to contain only strings.
447 +     * The following code can be used to dump the queue into a newly
448 +     * allocated array of {@code String}:
449 +     *
450 +     * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
451 +     *
452 +     * Note that {@code toArray(new Object[0])} is identical in function to
453 +     * {@code toArray()}.
454 +     *
455 +     * @param a the array into which the elements of the queue are to
456 +     *          be stored, if it is big enough; otherwise, a new array of the
457 +     *          same runtime type is allocated for this purpose.
458 +     * @return an array containing all of the elements in this queue
459 +     * @throws ArrayStoreException if the runtime type of the specified array
460 +     *         is not a supertype of the runtime type of every element in
461 +     *         this queue
462 +     * @throws NullPointerException if the specified array is null
463 +     */
464 +    @SuppressWarnings("unchecked")
465 +    public <T> T[] toArray(T[] a) {
466 +        final int size = this.size;
467 +        if (a.length < size)
468 +            // Make a new array of a's runtime type, but my contents:
469 +            return (T[]) Arrays.copyOf(queue, size, a.getClass());
470 +        System.arraycopy(queue, 0, a, 0, size);
471 +        if (a.length > size)
472 +            a[size] = null;
473 +        return a;
474 +    }
475 +
476 +    /**
477       * Returns an iterator over the elements in this queue. The iterator
478       * does not return the elements in any particular order.
479       *
480 <     * @return an iterator over the elements in this queue.
480 >     * @return an iterator over the elements in this queue
481       */
482      public Iterator<E> iterator() {
483          return new Itr();
484      }
485  
486 <    private class Itr implements Iterator<E> {
383 <
486 >    private final class Itr implements Iterator<E> {
487          /**
488           * Index (into queue array) of element to be returned by
489           * subsequent call to next.
490           */
491 <        private int cursor = 1;
491 >        private int cursor;
492  
493          /**
494           * Index of element returned by most recent call to next,
495           * unless that element came from the forgetMeNot list.
496 <         * Reset to 0 if element is deleted by a call to remove.
496 >         * Set to -1 if element is deleted by a call to remove.
497           */
498 <        private int lastRet = 0;
498 >        private int lastRet = -1;
499  
500          /**
501 <         * The modCount value that the iterator believes that the backing
399 <         * List should have.  If this expectation is violated, the iterator
400 <         * has detected concurrent modification.
401 <         */
402 <        private int expectedModCount = modCount;
403 <
404 <        /**
405 <         * A list of elements that were moved from the unvisited portion of
501 >         * A queue of elements that were moved from the unvisited portion of
502           * the heap into the visited portion as a result of "unlucky" element
503           * removals during the iteration.  (Unlucky element removals are those
504 <         * that require a fixup instead of a fixdown.)  We must visit all of
504 >         * that require a siftup instead of a siftdown.)  We must visit all of
505           * the elements in this list to complete the iteration.  We do this
506           * after we've completed the "normal" iteration.
507           *
508           * We expect that most iterations, even those involving removals,
509 <         * will not use need to store elements in this field.
509 >         * will not need to store elements in this field.
510           */
511 <        private ArrayList<E> forgetMeNot = null;
511 >        private ArrayDeque<E> forgetMeNot;
512  
513          /**
514           * Element returned by the most recent call to next iff that
515           * element was drawn from the forgetMeNot list.
516           */
517 <        private Object lastRetElt = null;
517 >        private E lastRetElt;
518 >
519 >        /**
520 >         * The modCount value that the iterator believes that the backing
521 >         * Queue should have.  If this expectation is violated, the iterator
522 >         * has detected concurrent modification.
523 >         */
524 >        private int expectedModCount = modCount;
525 >
526 >        Itr() {}                        // prevent access constructor creation
527  
528          public boolean hasNext() {
529 <            return cursor <= size || forgetMeNot != null;
529 >            return cursor < size ||
530 >                (forgetMeNot != null && !forgetMeNot.isEmpty());
531          }
532  
533 +        @SuppressWarnings("unchecked")
534          public E next() {
535 <            checkForComodification();
536 <            E result;
537 <            if (cursor <= size) {
538 <                result = (E) queue[cursor];
539 <                lastRet = cursor++;
540 <            }
541 <            else if (forgetMeNot == null)
542 <                throw new NoSuchElementException();
543 <            else {
437 <                int remaining = forgetMeNot.size();
438 <                result = forgetMeNot.remove(remaining - 1);
439 <                if (remaining == 1)
440 <                    forgetMeNot = null;
441 <                lastRet = 0;
442 <                lastRetElt = result;
535 >            if (expectedModCount != modCount)
536 >                throw new ConcurrentModificationException();
537 >            if (cursor < size)
538 >                return (E) queue[lastRet = cursor++];
539 >            if (forgetMeNot != null) {
540 >                lastRet = -1;
541 >                lastRetElt = forgetMeNot.poll();
542 >                if (lastRetElt != null)
543 >                    return lastRetElt;
544              }
545 <            return result;
545 >            throw new NoSuchElementException();
546          }
547  
548          public void remove() {
549 <            checkForComodification();
550 <
551 <            if (lastRet != 0) {
549 >            if (expectedModCount != modCount)
550 >                throw new ConcurrentModificationException();
551 >            if (lastRet != -1) {
552                  E moved = PriorityQueue.this.removeAt(lastRet);
553 <                lastRet = 0;
554 <                if (moved == null) {
553 >                lastRet = -1;
554 >                if (moved == null)
555                      cursor--;
556 <                } else {
556 >                else {
557                      if (forgetMeNot == null)
558 <                        forgetMeNot = new ArrayList<E>();
558 >                        forgetMeNot = new ArrayDeque<>();
559                      forgetMeNot.add(moved);
560                  }
561              } else if (lastRetElt != null) {
562 <                PriorityQueue.this.remove(lastRetElt);
562 >                PriorityQueue.this.removeEq(lastRetElt);
563                  lastRetElt = null;
564              } else {
565                  throw new IllegalStateException();
566              }
466
567              expectedModCount = modCount;
568          }
469
470        final void checkForComodification() {
471            if (modCount != expectedModCount)
472                throw new ConcurrentModificationException();
473        }
569      }
570  
571      public int size() {
# Line 478 | Line 573 | public class PriorityQueue<E> extends Ab
573      }
574  
575      /**
576 <     * Remove all elements from the priority queue.
576 >     * Removes all of the elements from this priority queue.
577 >     * The queue will be empty after this call returns.
578       */
579      public void clear() {
580          modCount++;
581 <
486 <        // Null out element references to prevent memory leak
487 <        for (int i=1; i<=size; i++)
581 >        for (int i = 0; i < size; i++)
582              queue[i] = null;
489
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 <
593 <        E result = (E) queue[1];
594 <        queue[1] = queue[size];
595 <        queue[size--] = null;  // Drop extra ref to prevent memory leak
596 <        if (size > 1)
502 <            fixDown(1);
503 <
592 >        E result = (E) queue[0];
593 >        E x = (E) queue[s];
594 >        queue[s] = null;
595 >        if (s != 0)
596 >            siftDown(0, x);
597          return result;
598      }
599  
600      /**
601 <     * Removes and returns the ith element from queue.  (Recall that queue
509 <     * is one-based, so 1 <= i <= size.)
601 >     * Removes the ith element from queue.
602       *
603 <     * Normally this method leaves the elements at positions from 1 up to i-1,
604 <     * inclusive, untouched.  Under these circumstances, it returns null.
605 <     * Occasionally, in order to maintain the heap invariant, it must move
606 <     * the last element of the list to some index in the range [2, i-1],
607 <     * and move the element previously at position (i/2) to position i.
608 <     * Under these circumstances, this method returns the element that was
609 <     * previously at the end of the list and is now at some position between
610 <     * 2 and i-1 inclusive.
611 <     */
612 <    private E removeAt(int i) {
613 <        assert i > 0 && i <= size;
603 >     * Normally this method leaves the elements at up to i-1,
604 >     * inclusive, untouched.  Under these circumstances, it returns
605 >     * null.  Occasionally, in order to maintain the heap invariant,
606 >     * it must swap a later element of the list with one earlier than
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 traversing elements.
611 >     */
612 >    @SuppressWarnings("unchecked")
613 >    E removeAt(int i) {
614 >        // assert i >= 0 && i < size;
615          modCount++;
616 <
617 <        E moved = (E) queue[size];
618 <        queue[i] = moved;
619 <        queue[size--] = null;  // Drop extra ref to prevent memory leak
620 <        if (i <= size) {
621 <            fixDown(i);
616 >        int s = --size;
617 >        if (s == i) // removed last element
618 >            queue[i] = null;
619 >        else {
620 >            E moved = (E) queue[s];
621 >            queue[s] = null;
622 >            siftDown(i, moved);
623              if (queue[i] == moved) {
624 <                fixUp(i);
624 >                siftUp(i, moved);
625                  if (queue[i] != moved)
626                      return moved;
627              }
# Line 536 | Line 630 | public class PriorityQueue<E> extends Ab
630      }
631  
632      /**
633 <     * Establishes the heap invariant (described above) assuming the heap
634 <     * satisfies the invariant except possibly for the leaf-node indexed by k
635 <     * (which may have a nextExecutionTime less than its parent's).
636 <     *
637 <     * This method functions by "promoting" queue[k] up the hierarchy
638 <     * (by swapping it with its parent) repeatedly until queue[k]
639 <     * is greater than or equal to its parent.
640 <     */
641 <    private void fixUp(int k) {
642 <        if (comparator == null) {
643 <            while (k > 1) {
644 <                int j = k >> 1;
645 <                if (((Comparable<E>)queue[j]).compareTo((E)queue[k]) <= 0)
646 <                    break;
647 <                Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
648 <                k = j;
649 <            }
650 <        } else {
651 <            while (k > 1) {
652 <                int j = k >>> 1;
653 <                if (comparator.compare((E)queue[j], (E)queue[k]) <= 0)
654 <                    break;
655 <                Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
656 <                k = j;
657 <            }
633 >     * Inserts item x at position k, maintaining heap invariant by
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
638 >     * Comparable and Comparator versions are separated into different
639 >     * methods that are otherwise identical. (Similarly for siftDown.)
640 >     *
641 >     * @param k the position to fill
642 >     * @param x the item to insert
643 >     */
644 >    private void siftUp(int k, E x) {
645 >        if (comparator != null)
646 >            siftUpUsingComparator(k, x);
647 >        else
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)
658 >                break;
659 >            queue[k] = e;
660 >            k = parent;
661 >        }
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)
671 >                break;
672 >            queue[k] = e;
673 >            k = parent;
674          }
675 +        queue[k] = x;
676      }
677  
678      /**
679 <     * Establishes the heap invariant (described above) in the subtree
680 <     * rooted at k, which is assumed to satisfy the heap invariant except
681 <     * possibly for node k itself (which may be greater than its children).
682 <     *
683 <     * This method functions by "demoting" queue[k] down the hierarchy
684 <     * (by swapping it with its smaller child) repeatedly until queue[k]
685 <     * is less than or equal to its children.
686 <     */
687 <    private void fixDown(int k) {
688 <        int j;
689 <        if (comparator == null) {
690 <            while ((j = k << 1) <= size && (j > 0)) {
691 <                if (j<size &&
692 <                    ((Comparable<E>)queue[j]).compareTo((E)queue[j+1]) > 0)
693 <                    j++; // j indexes smallest kid
694 <
695 <                if (((Comparable<E>)queue[k]).compareTo((E)queue[j]) <= 0)
696 <                    break;
697 <                Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
698 <                k = j;
699 <            }
700 <        } else {
701 <            while ((j = k << 1) <= size && (j > 0)) {
702 <                if (j<size &&
703 <                    comparator.compare((E)queue[j], (E)queue[j+1]) > 0)
704 <                    j++; // j indexes smallest kid
705 <                if (comparator.compare((E)queue[k], (E)queue[j]) <= 0)
706 <                    break;
707 <                Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
597 <                k = j;
598 <            }
679 >     * Inserts item x at position k, maintaining heap invariant by
680 >     * demoting x down the tree repeatedly until it is less than or
681 >     * equal to its children or is a leaf.
682 >     *
683 >     * @param k the position to fill
684 >     * @param x the item to insert
685 >     */
686 >    private void siftDown(int k, E x) {
687 >        if (comparator != null)
688 >            siftDownUsingComparator(k, x);
689 >        else
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
697 >        while (k < half) {
698 >            int child = (k << 1) + 1; // assume left child is least
699 >            Object c = queue[child];
700 >            int right = child + 1;
701 >            if (right < size &&
702 >                ((Comparable<? super E>) c).compareTo((E) queue[right]) > 0)
703 >                c = queue[child = right];
704 >            if (key.compareTo((E) c) <= 0)
705 >                break;
706 >            queue[k] = c;
707 >            k = child;
708          }
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) {
716 +            int child = (k << 1) + 1;
717 +            Object c = queue[child];
718 +            int right = child + 1;
719 +            if (right < size &&
720 +                comparator.compare((E) c, (E) queue[right]) > 0)
721 +                c = queue[child = right];
722 +            if (comparator.compare(x, (E) c) <= 0)
723 +                break;
724 +            queue[k] = c;
725 +            k = child;
726 +        }
727 +        queue[k] = x;
728      }
729  
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/2; i >= 1; i--)
738 <            fixDown(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 this collection, or <tt>null</tt>
749 <     * if this collection is sorted according to its elements natural ordering
750 <     * (using <tt>Comparable</tt>).
751 <     *
752 <     * @return the comparator used to order this collection, or <tt>null</tt>
753 <     * if this collection is sorted according to its elements natural ordering.
748 >     * Returns the comparator used to order the elements in this
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 >     *         {@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
625 <     * is, serialize it).
761 >     * Saves this queue to a stream (that is, serializes it).
762       *
627     * @serialData The length of the array backing the instance is
628     * emitted (int), followed by all of its elements (each an
629     * <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 <        s.writeInt(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=1; i<=size; i++)
777 >        // Write out all elements in the "proper order".
778 >        for (int i = 0; i < size; i++)
779              s.writeObject(queue[i]);
780      }
781  
782      /**
783 <     * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
784 <     * deserialize it).
783 >     * Reconstitutes the {@code PriorityQueue} instance from a stream
784 >     * (that is, deserializes it).
785 >     *
786       * @param s the stream
787 +     * @throws ClassNotFoundException if the class of a serialized object
788 +     *         could not be found
789 +     * @throws java.io.IOException if an I/O error occurs
790       */
791      private void readObject(java.io.ObjectInputStream s)
792          throws java.io.IOException, ClassNotFoundException {
793          // Read in size, and any hidden stuff
794          s.defaultReadObject();
795  
796 <        // Read in array length and allocate array
797 <        int arrayLength = s.readInt();
798 <        queue = new Object[arrayLength];
799 <
800 <        // Read in all elements in the proper order.
801 <        for (int i=1; i<=size; i++)
802 <            queue[i] = (E) s.readObject();
796 >        // Read in (and discard) array length
797 >        s.readInt();
798 >
799 >        SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, size);
800 >        queue = new Object[size];
801 >
802 >        // Read in all elements.
803 >        for (int i = 0; i < size; i++)
804 >            queue[i] = s.readObject();
805 >
806 >        // Elements are guaranteed to be in "proper order", but the
807 >        // spec has never explained what that might be.
808 >        heapify();
809      }
810  
811 +    /**
812 +     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
813 +     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
814 +     * queue. The spliterator does not traverse elements in any particular order
815 +     * (the {@link Spliterator#ORDERED ORDERED} characteristic is not reported).
816 +     *
817 +     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
818 +     * {@link Spliterator#SUBSIZED}, and {@link Spliterator#NONNULL}.
819 +     * Overriding implementations should document the reporting of additional
820 +     * characteristic values.
821 +     *
822 +     * @return a {@code Spliterator} over the elements in this queue
823 +     * @since 1.8
824 +     */
825 +    public final Spliterator<E> spliterator() {
826 +        return new PriorityQueueSpliterator(0, -1, 0);
827 +    }
828 +
829 +    final class PriorityQueueSpliterator implements Spliterator<E> {
830 +        private int index;            // current index, modified on advance/split
831 +        private int fence;            // -1 until first use
832 +        private int expectedModCount; // initialized when fence set
833 +
834 +        /** Creates new spliterator covering the given range. */
835 +        PriorityQueueSpliterator(int origin, int fence, int expectedModCount) {
836 +            this.index = origin;
837 +            this.fence = fence;
838 +            this.expectedModCount = expectedModCount;
839 +        }
840 +
841 +        private int getFence() { // initialize fence to size on first use
842 +            int hi;
843 +            if ((hi = fence) < 0) {
844 +                expectedModCount = modCount;
845 +                hi = fence = size;
846 +            }
847 +            return hi;
848 +        }
849 +
850 +        public PriorityQueueSpliterator trySplit() {
851 +            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
852 +            return (lo >= mid) ? null :
853 +                new PriorityQueueSpliterator(lo, index = mid, expectedModCount);
854 +        }
855 +
856 +        @SuppressWarnings("unchecked")
857 +        public void forEachRemaining(Consumer<? super E> action) {
858 +            if (action == null)
859 +                throw new NullPointerException();
860 +            if (fence < 0) { fence = size; expectedModCount = modCount; }
861 +            final Object[] a = queue;
862 +            int i, hi; E e;
863 +            for (i = index, index = hi = fence; i < hi; i++) {
864 +                if ((e = (E) a[i]) == null)
865 +                    break;      // must be CME
866 +                action.accept(e);
867 +            }
868 +            if (modCount != expectedModCount)
869 +                throw new ConcurrentModificationException();
870 +        }
871 +
872 +        @SuppressWarnings("unchecked")
873 +        public boolean tryAdvance(Consumer<? super E> action) {
874 +            if (action == null)
875 +                throw new NullPointerException();
876 +            if (fence < 0) { fence = size; expectedModCount = modCount; }
877 +            int i;
878 +            if ((i = index) < fence) {
879 +                index = i + 1;
880 +                E e;
881 +                if ((e = (E) queue[i]) == null
882 +                    || modCount != expectedModCount)
883 +                    throw new ConcurrentModificationException();
884 +                action.accept(e);
885 +                return true;
886 +            }
887 +            return false;
888 +        }
889 +
890 +        public long estimateSize() {
891 +            return getFence() - index;
892 +        }
893 +
894 +        public int characteristics() {
895 +            return Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.NONNULL;
896 +        }
897 +    }
898 +
899 +    /**
900 +     * @throws NullPointerException {@inheritDoc}
901 +     */
902 +    @SuppressWarnings("unchecked")
903 +    public void forEach(Consumer<? super E> action) {
904 +        Objects.requireNonNull(action);
905 +        final int expectedModCount = modCount;
906 +        final Object[] es = queue;
907 +        for (int i = 0, n = size; i < n; i++)
908 +            action.accept((E) es[i]);
909 +        if (expectedModCount != modCount)
910 +            throw new ConcurrentModificationException();
911 +    }
912   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines