PriorityQueue<E> · Java
remove(Object) / contains
Finds an arbitrary element by equals(): a linear search.
public boolean remove(Object o); public boolean contains(Object o)
Complexity
| Worst case | O(n) |
|---|---|
| Extra space | O(1) |
The documented complexity: linear time. A heap knows only where the minimum is, so finding anything else is a scan; restoring order afterwards is O(log n).
Tested example
PriorityQueue<Integer> heap = new PriorityQueue<>(List.of(4, 2, 9, 7));
assert heap.remove(Integer.valueOf(9)); // linear search, then re-heapify: O(n)
assert !heap.contains(9); // contains is linear too
assert heap.size() == 3;
Parameters
- o
- The element.
Behaviour
- Returns
- Whether it was found (and removed).
- Errors and preconditions
- None.
- Changes
- remove(Object) removes one matching element and restores the heap.
- Memory and invalidation
- No allocation.