PriorityQueue<E> · Java

offer / add

Inserts an element and sifts it up.

public boolean offer(E e); public boolean add(E e)

Complexity

Worst caseO(log n)
Extra spaceO(1) amortized

The documented complexity: O(log n) for offer, poll, remove() and add. Sift-up swaps with the parent along one root-to-leaf path.

Tested example

PriorityQueue<Integer> heap = new PriorityQueue<>(); // natural order: smallest first
heap.offer(5);
heap.offer(1);
heap.offer(3);
assert heap.peek() == 1;
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
maxHeap.addAll(List.of(5, 1, 3));
assert maxHeap.peek() == 5;
Runs in the test suite on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/test/java/dev/bekadan/dsa/collections/PriorityQueueExamples.java

Parameters

e
Non-null element, comparable with the others.

Behaviour

Returns
true.
Errors and preconditions
NullPointerException for null; ClassCastException if elements are not mutually comparable.
Changes
size increases by 1.
Memory and invalidation
May grow the array.