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 caseO(n)
Extra spaceO(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;
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

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.