PriorityQueue<E> · Java
offer / add
Inserts an element and sifts it up.
public boolean offer(E e); public boolean add(E e)
Complexity
| Worst case | O(log n) |
|---|---|
| Extra space | O(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;
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.