Comparator
provided at queue construction time, depending on which constructor is
used. A priority queue does not permit null
elements.
A priority queue relying on natural ordering also does not permit
insertion of non-comparable objects (doing so may result in
ClassCastException
).
The head of this queue is the least element
with respect to the specified ordering. If multiple elements are
tied for least value, the head is one of those elements -- ties are
broken arbitrarily. The queue retrieval operations poll
,
remove
, peek
, and element
access the
element at the head of the queue.
A priority queue is unbounded, but has an internal capacity governing the size of an array used to store the elements on the queue. It is always at least as large as the queue size. As elements are added to a priority queue, its capacity grows automatically. The details of the growth policy are not specified.
This class and its iterator implement all of the
optional methods of the Collection
and Iterator
interfaces. The Iterator provided in method iterator()
and the Spliterator provided in method spliterator()
are not guaranteed to traverse the elements of
the priority queue in any particular order. If you need ordered
traversal, consider using Arrays.sort(pq.toArray())
.
Note that this implementation is not synchronized.
Multiple threads should not access a PriorityQueue
instance concurrently if any of the threads modifies the queue.
Instead, use the thread-safe java.
class.
Implementation Note
this implementation provides
O(log(n)) time for the enqueuing and dequeuing methods
(offer
, poll
, remove()
and add
);
linear time for the remove(Object)
and contains(Object)
methods; and constant time for the retrieval methods
(peek
, element
, and size
).
This class is a member of the Java Collections Framework.
Modifier and Type | Class and Description |
---|---|
private class | |
pack-priv class |
Modifier and Type | Field and Description |
---|---|
private final Comparator | comparator
The comparator, or null if priority queue uses elements' natural ordering. |
private static final int | |
pack-priv transient int | modCount
The number of times this priority queue has been structurally modified. |
pack-priv transient Object[] | queue
Priority queue represented as a balanced binary heap: the two children of queue[n] are queue[2*n+1] and queue[2*(n+1)]. |
private static final long | |
pack-priv int | size
The number of elements in the priority queue. |
Access | Constructor and Description |
---|---|
public | PriorityQueue()
Creates a |
public | PriorityQueue(int
the initial capacity for this priority queue initialCapacity)Creates a |
public | PriorityQueue(Comparator<? super E>
the comparator that will be used to order this
priority queue. If comparator)null , the natural ordering of the elements will be used.Creates a |
public | PriorityQueue(int
the initial capacity for this priority queue initialCapacity, Comparator<? super E> the comparator that will be used to order this
priority queue. If comparator)null , the natural ordering of the elements will be used.Creates a |
public | PriorityQueue(Collection<? extends E>
the collection whose elements are to be placed
into this priority queue c)Creates a |
public | PriorityQueue(PriorityQueue<? extends E>
the priority queue whose elements are to be placed
into this priority queue c)Creates a |
public | PriorityQueue(SortedSet<? extends E>
the sorted set whose elements are to be placed
into this priority queue c)Creates a |
Modifier and Type | Method and Description |
---|---|
public boolean | add(E
the element to add e)Overrides java. Implements java. Inserts the specified element into this priority queue. |
private boolean | |
public void | clear()
Overrides java. Implements java. Removes all of the elements from this priority queue. |
public Comparator | Returns: the comparator used to order this queue, ornull if this queue is sorted according to the
natural ordering of its elementsReturns the comparator used to order the elements in this
queue, or |
public boolean | Returns: true if this queue contains the specified elementobject to be checked for containment in this queue o)Overrides java. Implements java. Returns |
private static Object[] | |
public void | forEach(Consumer<? super E>
The action to be performed for each element action)Overrides default java. Performs the given action for each element of the |
private void | |
private void | heapify()
Establishes the heap invariant (described above) in the entire tree, assuming nothing about the order of the elements prior to the call. |
private int | |
private void | |
private void | initFromCollection(Collection<? extends E>
the collection c)Initializes queue array with elements from the given Collection. |
private void | |
private static boolean | |
public Iterator | Returns: an iterator over the elements in this queueImplements abstract java. Implements java. Returns an iterator over the elements in this queue. |
private static long[] | |
public boolean | offer(E
the element to add e)Implements java. Inserts the specified element into this priority queue. |
public E | peek()
Implements java. Retrieves, but does not remove, the head of this queue,
or returns |
public E | poll()
Implements java. Retrieves and removes the head of this queue,
or returns |
private void | readObject(ObjectInputStream
the stream s)Reconstitutes the |
public boolean | Returns: true if this queue changed as a result of the callelement to be removed from this queue, if present o)Overrides java. Implements java. Removes a single instance of the specified element from this queue, if it is present. |
public boolean | removeAll(Collection<?>
collection containing elements to be removed from this collection c)Overrides java. Implements java. Removes all of this collection's elements that are also contained in the specified collection (optional operation). |
pack-priv E | |
pack-priv void | |
public boolean | removeIf(Predicate<? super E>
a predicate which returns filter)true for elements to be
removedOverrides default java. Removes all of the elements of this collection that satisfy the given predicate (optional operation). |
public boolean | retainAll(Collection<?>
collection containing elements to be retained in this collection c)Overrides java. Implements java. Retains only the elements in this collection that are contained in the specified collection (optional operation). |
private static void | |
private void | siftDown(int
the position to fill k, E the item to insert x)Inserts item x at position k, maintaining heap invariant by demoting x down the tree repeatedly until it is less than or equal to its children or is a leaf. |
private static <T> void | |
private static <T> void | |
private void | siftUp(int
the position to fill k, E the item to insert x)Inserts item x at position k, maintaining heap invariant by promoting x up the tree until it is greater than or equal to its parent, or is the root. |
private static <T> void | |
private static <T> void | |
public int | size()
Implements abstract java. Implements java. Returns the number of elements in this collection. |
public final Spliterator | Returns: aSpliterator over the elements in this queueOverrides default java. Creates a late-binding
and fail-fast |
public Object[] | Returns: an array containing all of the elements in this queueOverrides java. Implements java. Returns an array containing all of the elements in this queue. |
public <T> T[] | Returns: an array containing all of the elements in this queuethe array into which the elements of the queue are to
be stored, if it is big enough; otherwise, a new array of the
same runtime type is allocated for this purpose. a)Overrides java. Implements java. Returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array. |
private void |
comparator | back to summary |
---|---|
private final Comparator<? super E> comparator The comparator, or null if priority queue uses elements' natural ordering.
|
DEFAULT_INITIAL_CAPACITY | back to summary |
---|---|
private static final int DEFAULT_INITIAL_CAPACITY |
modCount | back to summary |
---|---|
pack-priv transient int modCount The number of times this priority queue has been structurally modified. See AbstractList for gory details. |
queue | back to summary |
---|---|
pack-priv transient Object[] queue Priority queue represented as a balanced binary heap: the two children of queue[n] are queue[2*n+1] and queue[2*(n+1)]. The priority queue is ordered by comparator, or by the elements' natural ordering, if comparator is null: For each node n in the heap and each descendant d of n, n <= d. The element with the lowest value is in queue[0], assuming the queue is nonempty. |
serialVersionUID | back to summary |
---|---|
private static final long serialVersionUID
|
size | back to summary |
---|---|
pack-priv int size The number of elements in the priority queue. |
PriorityQueue | back to summary |
---|---|
public PriorityQueue() Creates a |
PriorityQueue | back to summary |
---|---|
public PriorityQueue(int initialCapacity) Creates a
|
PriorityQueue | back to summary |
---|---|
public PriorityQueue(Comparator<? super E> comparator) Creates a
|
PriorityQueue | back to summary |
---|---|
public PriorityQueue(int initialCapacity, Comparator<? super E> comparator) Creates a
|
PriorityQueue | back to summary |
---|---|
public PriorityQueue(Collection<? extends E> c) Creates a
|
PriorityQueue | back to summary |
---|---|
public PriorityQueue(PriorityQueue<? extends E> c) Creates a
|
PriorityQueue | back to summary |
---|---|
public PriorityQueue(SortedSet<? extends E> c) Creates a
|
add | back to summary |
---|---|
public boolean add(E e) Overrides java. Implements java. Inserts the specified element into this priority queue.
|
bulkRemove | back to summary |
---|---|
private boolean bulkRemove(Predicate<? super E> filter) Implementation of bulk remove methods. |
clear | back to summary |
---|---|
public void clear() Overrides java. Implements java. Removes all of the elements from this priority queue. The queue will be empty after this call returns. |
comparator | back to summary |
---|---|
public Comparator Returns the comparator used to order the elements in this
queue, or
|
contains | back to summary |
---|---|
public boolean contains(Object o) Overrides java. Implements java. Returns
|
ensureNonEmpty | back to summary |
---|---|
private static Object[] ensureNonEmpty(Object[] es) Ensures that queue[0] exists, helping peek() and poll(). |
forEach | back to summary |
---|---|
public void forEach(Consumer<? super E> action) Overrides default java. Doc from java. Performs the given action for each element of the The behavior of this method is unspecified if the action performs side-effects that modify the underlying source of elements, unless an overriding class has specified a concurrent modification policy.
|
grow | back to summary |
---|---|
private void grow(int minCapacity) Increases the capacity of the array.
|
heapify | back to summary |
---|---|
private void heapify() Establishes the heap invariant (described above) in the entire tree, assuming nothing about the order of the elements prior to the call. This classic algorithm due to Floyd (1964) is known to be O(size). |
indexOf | back to summary |
---|---|
private int indexOf(Object o) |
initElementsFromCollection | back to summary |
---|---|
private void initElementsFromCollection(Collection<? extends E> c) |
initFromCollection | back to summary |
---|---|
private void initFromCollection(Collection<? extends E> c) Initializes queue array with elements from the given Collection.
|
initFromPriorityQueue | back to summary |
---|---|
private void initFromPriorityQueue(PriorityQueue<? extends E> c) |
isClear | back to summary |
---|---|
private static boolean isClear(long[] bits, int i) |
iterator | back to summary |
---|---|
public Iterator Implements abstract java. Implements java. Returns an iterator over the elements in this queue. The iterator does not return the elements in any particular order.
|
nBits | back to summary |
---|---|
private static long[] nBits(int n) |
offer | back to summary |
---|---|
public boolean offer(E e) Implements java. Inserts the specified element into this priority queue.
|
peek | back to summary |
---|---|
public E peek() Implements java. Doc from java. Retrieves, but does not remove, the head of this queue,
or returns
|
poll | back to summary |
---|---|
public E poll() Implements java. Doc from java. Retrieves and removes the head of this queue,
or returns
|
readObject | back to summary |
---|---|
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException Reconstitutes the
|
remove | back to summary |
---|---|
public boolean remove(Object o) Overrides java. Implements java. Removes a single instance of the specified element from this queue,
if it is present. More formally, removes an element
|
removeAll | back to summary |
---|---|
public boolean removeAll(Collection<?> c) Overrides java. Implements java. Doc from java. Removes all of this collection's elements that are also contained in the specified collection (optional operation). After this call returns, this collection will contain no elements in common with the specified collection.
|
removeAt | back to summary |
---|---|
pack-priv E removeAt(int i) Removes the ith element from queue. Normally this method leaves the elements at up to i-1, inclusive, untouched. Under these circumstances, it returns null. Occasionally, in order to maintain the heap invariant, it must swap a later element of the list with one earlier than i. Under these circumstances, this method returns the element that was previously at the end of the list and is now at some position before i. This fact is used by iterator.remove so as to avoid missing traversing elements. |
removeEq | back to summary |
---|---|
pack-priv void removeEq(Object o) Identity-based version for use in Itr.remove.
|
removeIf | back to summary |
---|---|
public boolean removeIf(Predicate<? super E> filter) Overrides default java. Doc from java. Removes all of the elements of this collection that satisfy the given predicate (optional operation). Errors or runtime exceptions thrown during iteration or by the predicate are relayed to the caller.
|
retainAll | back to summary |
---|---|
public boolean retainAll(Collection<?> c) Overrides java. Implements java. Doc from java. Retains only the elements in this collection that are contained in the specified collection (optional operation). In other words, removes from this collection all of its elements that are not contained in the specified collection.
|
setBit | back to summary |
---|---|
private static void setBit(long[] bits, int i) |
siftDown | back to summary |
---|---|
private void siftDown(int k, E x) Inserts item x at position k, maintaining heap invariant by demoting x down the tree repeatedly until it is less than or equal to its children or is a leaf.
|
siftDownComparable | back to summary |
---|---|
private static <T> void siftDownComparable(int k, T x, Object[] es, int n) |
siftDownUsingComparator | back to summary |
---|---|
private static <T> void siftDownUsingComparator(int k, T x, Object[] es, int n, Comparator<? super T> cmp) |
siftUp | back to summary |
---|---|
private void siftUp(int k, E x) Inserts item x at position k, maintaining heap invariant by promoting x up the tree until it is greater than or equal to its parent, or is the root. To simplify and speed up coercions and comparisons, the Comparable and Comparator versions are separated into different methods that are otherwise identical. (Similarly for siftDown.)
|
siftUpComparable | back to summary |
---|---|
private static <T> void siftUpComparable(int k, T x, Object[] es) |
siftUpUsingComparator | back to summary |
---|---|
private static <T> void siftUpUsingComparator(int k, T x, Object[] es, Comparator<? super T> cmp) |
size | back to summary |
---|---|
public int size() Implements abstract java. Implements java. Doc from java. Returns the number of elements in this collection. If this collection
contains more than
|
spliterator | back to summary |
---|---|
public final Spliterator Overrides default java. Creates a late-binding
and fail-fast The
|
toArray | back to summary |
---|---|
public Object[] toArray() Overrides java. Implements java. Returns an array containing all of the elements in this queue. The elements are in no particular order. The returned array will be "safe" in that no references to it are maintained by this queue. (In other words, this method must allocate a new array). The caller is thus free to modify the returned array. This method acts as bridge between array-based and collection-based APIs.
|
toArray | back to summary |
---|---|
public <T> T[] toArray(T[] a) Overrides java. Implements java. Returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array. The returned array elements are in no particular order. If the queue fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this queue. If the queue fits in the specified array with room to spare
(i.e., the array has more elements than the queue), the element in
the array immediately following the end of the collection is set to
Like the Suppose
Note that toArray(new Object[0]) is identical in function to
toArray() .
|
writeObject | back to summary |
---|---|
private void writeObject(ObjectOutputStream s) throws IOException Saves this queue to a stream (that is, serializes it).
|
Modifier and Type | Field and Description |
---|---|
private int | cursor
Index (into queue array) of element to be returned by subsequent call to next. |
private int | expectedModCount
The modCount value that the iterator believes that the backing Queue should have. |
private ArrayDeque | forgetMeNot
A queue of elements that were moved from the unvisited portion of the heap into the visited portion as a result of "unlucky" element removals during the iteration. |
private int | lastRet
Index of element returned by most recent call to next, unless that element came from the forgetMeNot list. |
private E | lastRetElt
Element returned by the most recent call to next iff that element was drawn from the forgetMeNot list. |
Access | Constructor and Description |
---|---|
pack-priv |
Modifier and Type | Method and Description |
---|---|
public boolean | |
public E | |
public void | remove()
Overrides default java. Removes from the underlying collection the last element returned by this iterator (optional operation). |
cursor | back to summary |
---|---|
private int cursor Index (into queue array) of element to be returned by subsequent call to next. |
expectedModCount | back to summary |
---|---|
private int expectedModCount The modCount value that the iterator believes that the backing Queue should have. If this expectation is violated, the iterator has detected concurrent modification. |
forgetMeNot | back to summary |
---|---|
private ArrayDeque<E> forgetMeNot A queue of elements that were moved from the unvisited portion of the heap into the visited portion as a result of "unlucky" element removals during the iteration. (Unlucky element removals are those that require a siftup instead of a siftdown.) We must visit all of the elements in this list to complete the iteration. We do this after we've completed the "normal" iteration. We expect that most iterations, even those involving removals, will not need to store elements in this field. |
lastRet | back to summary |
---|---|
private int lastRet Index of element returned by most recent call to next, unless that element came from the forgetMeNot list. Set to -1 if element is deleted by a call to remove. |
lastRetElt | back to summary |
---|---|
private E lastRetElt Element returned by the most recent call to next iff that element was drawn from the forgetMeNot list. |
Itr | back to summary |
---|---|
pack-priv Itr() |
hasNext | back to summary |
---|---|
public boolean hasNext() Implements java. Doc from java. Returns
|
next | back to summary |
---|---|
public E next() Implements java. Doc from java. Returns the next element in the iteration.
|
remove | back to summary |
---|---|
public void remove() Overrides default java. Doc from java. Removes from the underlying collection the last element returned
by this iterator (optional operation). This method can be called
only once per call to The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method, unless an overriding class has specified a concurrent modification policy.
The behavior of an iterator is unspecified if this method is called
after a call to the |
Modifier and Type | Field and Description |
---|---|
private int | |
private int | |
private int |
Access | Constructor and Description |
---|---|
pack-priv | PriorityQueueSpliterator(int origin, int fence, int expectedModCount)
Creates new spliterator covering the given range. |
Modifier and Type | Method and Description |
---|---|
public int | characteristics()
Implements java. Returns a set of characteristics of this Spliterator and its elements. |
public long | estimateSize()
Implements java. Returns an estimate of the number of elements that would be
encountered by a |
public void | forEachRemaining(Consumer<? super E>
The action action)Overrides default java. Performs the given action for each remaining element, sequentially in the current thread, until all elements have been processed or the action throws an exception. |
private int | |
public boolean | tryAdvance(Consumer<? super E>
The action whose operation is performed at-most once action)Implements java. If a remaining element exists: performs the given action on it,
returning |
public PriorityQueue | trySplit()
Implements java. If this spliterator can be partitioned, returns a Spliterator covering elements, that will, upon return from this method, not be covered by this Spliterator. |
expectedModCount | back to summary |
---|---|
private int expectedModCount |
fence | back to summary |
---|---|
private int fence |
index | back to summary |
---|---|
private int index |
PriorityQueueSpliterator | back to summary |
---|---|
pack-priv PriorityQueueSpliterator(int origin, int fence, int expectedModCount) Creates new spliterator covering the given range. |
characteristics | back to summary |
---|---|
public int characteristics() Implements java. Doc from java. Returns a set of characteristics of this Spliterator and its
elements. The result is represented as ORed values from If a Spliterator reports an inconsistent set of characteristics (either those returned from a single invocation or across multiple invocations), no guarantees can be made about any computation using this Spliterator.
|
estimateSize | back to summary |
---|---|
public long estimateSize() Implements java. Doc from java. Returns an estimate of the number of elements that would be
encountered by a If this Spliterator is
|
forEachRemaining | back to summary |
---|---|
public void forEachRemaining(Consumer<? super E> action) Overrides default java. Doc from java. Performs the given action for each remaining element, sequentially in
the current thread, until all elements have been processed or the action
throws an exception. If this Spliterator is Subsequent behavior of a spliterator is unspecified if the action throws an exception.
|
getFence | back to summary |
---|---|
private int getFence() |
tryAdvance | back to summary |
---|---|
public boolean tryAdvance(Consumer<? super E> action) Implements java. Doc from java. If a remaining element exists: performs the given action on it,
returning Subsequent behavior of a spliterator is unspecified if the action throws an exception.
|
trySplit | back to summary |
---|---|
public PriorityQueue Implements java. Doc from java. If this spliterator can be partitioned, returns a Spliterator covering elements, that will, upon return from this method, not be covered by this Spliterator. If this Spliterator is Unless this Spliterator covers an infinite number of elements,
repeated calls to
This method may return
|