1 |
|
/* |
2 |
< |
* Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. |
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 |
|
* This code is free software; you can redistribute it and/or modify it |
24 |
|
*/ |
25 |
|
|
26 |
|
package java.util; |
27 |
< |
import java.util.stream.Stream; |
28 |
< |
import java.util.Spliterator; |
29 |
< |
import java.util.stream.Streams; |
30 |
< |
import java.util.function.Block; |
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. |
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 {@code Arrays.sort(pq.toArray())}. |
62 |
|
* |
63 |
< |
* <p> <strong>Note that this implementation is not synchronized.</strong> |
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 |
70 |
< |
* O(log(n)) time for the enqueing and dequeing methods |
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}/../technotes/guides/collections/index.html"> |
77 |
> |
* <a href="{@docRoot}/java/util/package-summary.html#CollectionsFramework"> |
78 |
|
* Java Collections Framework</a>. |
79 |
|
* |
80 |
|
* @since 1.5 |
81 |
|
* @author Josh Bloch, Doug Lea |
82 |
< |
* @param <E> the type of elements held in this collection |
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 { |
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' |
113 |
|
* The number of times this priority queue has been |
114 |
|
* <i>structurally modified</i>. See AbstractList for gory details. |
115 |
|
*/ |
116 |
< |
transient int modCount = 0; // non-private to simplify nested class access |
116 |
> |
transient int modCount; // non-private to simplify nested class access |
117 |
|
|
118 |
|
/** |
119 |
|
* Creates a {@code PriorityQueue} with the default initial |
138 |
|
} |
139 |
|
|
140 |
|
/** |
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 |
|
* |
260 |
|
a = Arrays.copyOf(a, a.length, Object[].class); |
261 |
|
int len = a.length; |
262 |
|
if (len == 1 || this.comparator != null) |
263 |
< |
for (int i = 0; i < len; i++) |
264 |
< |
if (a[i] == null) |
263 |
> |
for (Object e : a) |
264 |
> |
if (e == null) |
265 |
|
throw new NullPointerException(); |
266 |
|
this.queue = a; |
267 |
|
this.size = a.length; |
339 |
|
int i = size; |
340 |
|
if (i >= queue.length) |
341 |
|
grow(i + 1); |
342 |
+ |
siftUp(i, e); |
343 |
|
size = i + 1; |
330 |
– |
if (i == 0) |
331 |
– |
queue[0] = e; |
332 |
– |
else |
333 |
– |
siftUp(i, e); |
344 |
|
return true; |
345 |
|
} |
346 |
|
|
405 |
|
* @return {@code true} if this queue contains the specified element |
406 |
|
*/ |
407 |
|
public boolean contains(Object o) { |
408 |
< |
return indexOf(o) != -1; |
408 |
> |
return indexOf(o) >= 0; |
409 |
|
} |
410 |
|
|
411 |
|
/** |
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> |
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()}. |
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()); |
488 |
|
* Index (into queue array) of element to be returned by |
489 |
|
* subsequent call to next. |
490 |
|
*/ |
491 |
< |
private int cursor = 0; |
491 |
> |
private int cursor; |
492 |
|
|
493 |
|
/** |
494 |
|
* Index of element returned by most recent call to next, |
508 |
|
* We expect that most iterations, even those involving removals, |
509 |
|
* will not need to store elements in this field. |
510 |
|
*/ |
511 |
< |
private ArrayDeque<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 E lastRetElt = null; |
517 |
> |
private E lastRetElt; |
518 |
|
|
519 |
|
/** |
520 |
|
* The modCount value that the iterator believes that the backing |
523 |
|
*/ |
524 |
|
private int expectedModCount = modCount; |
525 |
|
|
526 |
+ |
Itr() {} // prevent access constructor creation |
527 |
+ |
|
528 |
|
public boolean hasNext() { |
529 |
|
return cursor < size || |
530 |
|
(forgetMeNot != null && !forgetMeNot.isEmpty()); |
555 |
|
cursor--; |
556 |
|
else { |
557 |
|
if (forgetMeNot == null) |
558 |
< |
forgetMeNot = new ArrayDeque<E>(); |
558 |
> |
forgetMeNot = new ArrayDeque<>(); |
559 |
|
forgetMeNot.add(moved); |
560 |
|
} |
561 |
|
} else if (lastRetElt != null) { |
610 |
|
* avoid missing traversing elements. |
611 |
|
*/ |
612 |
|
@SuppressWarnings("unchecked") |
613 |
< |
private E removeAt(int i) { |
613 |
> |
E removeAt(int i) { |
614 |
|
// assert i >= 0 && i < size; |
615 |
|
modCount++; |
616 |
|
int s = --size; |
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 |
|
* |
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 |
|
/** |
760 |
|
/** |
761 |
|
* Saves this queue to a stream (that is, serializes it). |
762 |
|
* |
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. |
745 |
– |
* @param s the stream |
768 |
|
*/ |
769 |
|
private void writeObject(java.io.ObjectOutputStream s) |
770 |
|
throws java.io.IOException { |
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 { |
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. |
808 |
|
heapify(); |
809 |
|
} |
810 |
|
|
811 |
< |
// wrapping constructor in method avoids transient javac problems |
812 |
< |
final PriorityQueueSpliterator<E> spliterator(int origin, int fence, |
813 |
< |
int expectedModCount) { |
814 |
< |
return new PriorityQueueSpliterator(this, origin, fence, |
815 |
< |
expectedModCount); |
816 |
< |
} |
817 |
< |
|
818 |
< |
public Stream<E> stream() { |
819 |
< |
int flags = Streams.STREAM_IS_SIZED; |
820 |
< |
return Streams.stream |
821 |
< |
(() -> spliterator(0, size, modCount), flags); |
822 |
< |
} |
823 |
< |
public Stream<E> parallelStream() { |
824 |
< |
int flags = Streams.STREAM_IS_SIZED; |
825 |
< |
return Streams.parallelStream |
826 |
< |
(() -> spliterator(0, size, modCount), flags); |
827 |
< |
} |
828 |
< |
|
829 |
< |
/** Index-based split-by-two Spliterator */ |
830 |
< |
static final class PriorityQueueSpliterator<E> |
831 |
< |
implements Spliterator<E>, Iterator<E> { |
832 |
< |
private final PriorityQueue<E> pq; |
833 |
< |
private int index; // current index, modified on advance/split |
834 |
< |
private final int fence; // one past last index |
835 |
< |
private final int expectedModCount; // for comodification checks |
836 |
< |
|
837 |
< |
/** Create new spliterator covering the given range */ |
812 |
< |
PriorityQueueSpliterator(PriorityQueue<E> pq, int origin, int fence, |
813 |
< |
int expectedModCount) { |
814 |
< |
this.pq = pq; this.index = origin; this.fence = fence; |
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 |
< |
public PriorityQueueSpliterator<E> trySplit() { |
842 |
< |
int lo = index, mid = (lo + fence) >>> 1; |
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<E>(pq, lo, index = mid, |
822 |
< |
expectedModCount); |
853 |
> |
new PriorityQueueSpliterator(lo, index = mid, expectedModCount); |
854 |
|
} |
855 |
|
|
856 |
< |
public void forEach(Block<? super E> block) { |
857 |
< |
Object[] a; int i, hi; // hoist accesses and checks from loop |
858 |
< |
if (block == null) |
856 |
> |
@SuppressWarnings("unchecked") |
857 |
> |
public void forEachRemaining(Consumer<? super E> action) { |
858 |
> |
if (action == null) |
859 |
|
throw new NullPointerException(); |
860 |
< |
if ((a = pq.queue).length >= (hi = fence) && |
861 |
< |
(i = index) >= 0 && i < hi) { |
862 |
< |
index = hi; |
863 |
< |
do { |
864 |
< |
@SuppressWarnings("unchecked") E e = (E) a[i]; |
865 |
< |
block.accept(e); |
866 |
< |
} while (++i < hi); |
836 |
< |
if (pq.modCount != expectedModCount) |
837 |
< |
throw new ConcurrentModificationException(); |
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 |
< |
public boolean tryAdvance(Block<? super E> block) { |
873 |
< |
if (index >= 0 && index < fence) { |
874 |
< |
if (pq.modCount != expectedModCount) |
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 |
< |
@SuppressWarnings("unchecked") E e = |
846 |
< |
(E)pq.queue[index++]; |
847 |
< |
block.accept(e); |
884 |
> |
action.accept(e); |
885 |
|
return true; |
886 |
|
} |
887 |
|
return false; |
888 |
|
} |
889 |
|
|
890 |
< |
public long estimateSize() { return (long)(fence - index); } |
891 |
< |
public boolean hasExactSize() { return true; } |
892 |
< |
public boolean hasExactSplits() { return true; } |
856 |
< |
|
857 |
< |
// Iterator support |
858 |
< |
public Iterator<E> iterator() { return this; } |
859 |
< |
public void remove() { throw new UnsupportedOperationException(); } |
860 |
< |
public boolean hasNext() { return index >= 0 && index < fence; } |
890 |
> |
public long estimateSize() { |
891 |
> |
return getFence() - index; |
892 |
> |
} |
893 |
|
|
894 |
< |
public E next() { |
895 |
< |
if (index < 0 || index >= fence) |
864 |
< |
throw new NoSuchElementException(); |
865 |
< |
if (pq.modCount != expectedModCount) |
866 |
< |
throw new ConcurrentModificationException(); |
867 |
< |
@SuppressWarnings("unchecked") E e = |
868 |
< |
(E) pq.queue[index++]; |
869 |
< |
return e; |
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 |
|
} |