Java · Priority queue · container

PriorityQueue<E>

An unbounded binary min-heap: O(log n) offer and poll, O(1) peek, linear remove(Object) and contains.

import java.util.PriorityQueue;
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable

Java SE 25

Operations

OperationTimeWorst caseChanges the collection
offer / addO(log n)O(log n)Yes
poll / remove()O(log n)O(log n)Yes
peek / elementO(1)O(1)No
remove(Object) / containsO(n)O(n)Yes

"Time" shows the amortized, expected or average bound when one applies; open an operation for the full profile and its assumptions.

How it works

Representation
A balanced binary heap in an Object[] array (the documentation calls it a "priority heap"); queue[n]'s children are queue[2n+1] and queue[2n+2].
Ordering
The head is the least element by natural order or the given Comparator. The iterator does not traverse in priority order.
Duplicates
Allowed; null is not.
Mutability
Mutable; not thread-safe (PriorityBlockingQueue is).
Memory and ownership
Array grows as needed.
Equality and comparison
Ordering uses Comparable or the Comparator; remove(Object) and contains use equals().

Pitfalls

  • Printing or iterating shows array order, not sorted order; poll repeatedly (or sort a copy) for order.
  • Ties are broken arbitrarily: not FIFO for equal priorities.
  • Changing a field that affects ordering while the element is in the queue corrupts the heap; remove, change, re-add.

Alternatives

  • TreeSet / TreeMap when you need ordered iteration or O(log n) removal of arbitrary elements
  • PriorityBlockingQueue between threads

In other languages

References