PriorityQueue<E> · Java
poll / remove()
Removes and returns the head (the least element).
public E poll(); public E remove()
Complexity
| Worst case | O(log n) |
|---|---|
| Extra space | O(1) |
Move the last element to the root and sift it down.
Tested example
PriorityQueue<String> queue = new PriorityQueue<>(List.of("c", "a", "b"));
assert queue.poll().equals("a");
assert queue.poll().equals("b");
assert queue.poll().equals("c");
assert queue.poll() == null; // empty: null (remove() would throw)
Behaviour
- Returns
- The head; poll returns null when empty.
- Errors and preconditions
- remove(): NoSuchElementException when empty.
- Changes
- size decreases by 1.
- Memory and invalidation
- No allocation.