TheAlgorithms/Java · error · IllegalArgumentException

Item not found in the heap

Error message

Item not found in the heap

What it means

Thrown by GenericHeap.updatePriority(T) when the item is not a key in the internal HashMap<T,Integer> index. The heap tracks element positions by equality via the map, so an item that was never added, was already removed, or is a different instance whose equals() does not match a stored key fails the containsKey check. Note GenericHeap does not expose a public contains() method, so callers must track membership themselves.

Solutions

  1. Only call updatePriority on the exact object reference previously passed to add() and not yet removed.
  2. Maintain your own Set<T> of live items and check contains() before calling updatePriority.
  3. Ensure inserted objects have stable equals/hashCode (do not mutate fields used by hashCode after insertion).

Example fix

// before
heap.updatePriority(item);

// after
if (liveItems.contains(item)) {
    heap.updatePriority(item);
}
Defensive patterns

Strategy: validation

Validate before calling

// GenericHeap has no public contains(); track membership yourself
Set<T> live = new HashSet<>();
// on add: live.add(item);  on remove: live.remove(returned);
if (live.contains(item)) {
    heap.updatePriority(item);
}

Try / catch

try {
    heap.updatePriority(item);
} catch (IllegalArgumentException e) {
    // item not in heap; re-insert or skip
}

Prevention

When it happens

Trigger: Calling updatePriority on an item never inserted via add(); on an item already returned by remove() (it is dropped from the map); on a newly constructed object that is equal-but-distinct when equals/hashCode are inconsistent with storage.

Common situations: Dijkstra/A*-style relaxation where a node was already extracted; stale references kept after removal; mutable objects whose hashCode changed after insertion (map lookup then misses).

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/1634f97a6bd23ce5. Report an issue: GitHub.

Appendix: source

Thrown at src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java:144

     * @param j index of the second item
     */
    private void swap(int i, int j) {
        T ith = this.data.get(i);
        T jth = this.data.get(j);
        this.data.set(i, jth);
        this.data.set(j, ith);
        map.put(ith, j);
        map.put(jth, i);
    }

    /**
     * Updates the priority of the specified item by restoring the heap property.
     *
     * @param item the item whose priority is to be updated
     */
    public void updatePriority(T item) {
        if (!map.containsKey(item)) {
            throw new IllegalArgumentException("Item not found in the heap");
        }
        int index = map.get(item);
        upHeapify(index);
    }
}

View on GitHub (pinned to fdfb9a395b)