PriorityQueue<E> · Java
peek / element
Returns the head without removing it.
public E peek(); public E element()
Complexity
| Best case | O(1) |
|---|---|
| Worst case | O(1) |
| Extra space | O(1) |
The documented complexity: constant time for peek, element and size.
Tested example
PriorityQueue<Integer> heap = new PriorityQueue<>(List.of(4, 2, 9));
assert heap.peek() == 2; // constant time, nothing removed
assert heap.size() == 3;
// Iterating (or printing) shows the internal array order, not priority order.
Behaviour
- Returns
- The least element; peek returns null when empty.
- Errors and preconditions
- element(): NoSuchElementException when empty.
- Changes
- Nothing.
- Memory and invalidation
- No allocation.