TheAlgorithms/Java · error · IllegalStateException

Heap is empty

Error message

Heap is empty

What it means

Thrown by GenericHeap.remove() when the heap has no elements. remove() swaps the root with the last element, drops it, and re-heapifies; with size 0 there is no root to return and swap(0, -1) would be invalid. IllegalStateException signals an operation invoked in a wrong state rather than a bad argument.

Source

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

    }

    /**
     * Checks if the heap is empty.
     *
     * @return true if the heap is empty, false otherwise
     */
    public boolean isEmpty() {
        return this.size() == 0;
    }

    /**
     * Removes and returns the maximum item from the heap.
     *
     * @return the maximum item
     */
    public T remove() {
        if (isEmpty()) {
            throw new IllegalStateException("Heap is empty");
        }
        this.swap(0, this.size() - 1);
        T rv = this.data.remove(this.size() - 1);
        map.remove(rv);
        downHeapify(0);
        return rv;
    }

    /**
     * Restores the heap property by moving the item at the given index downwards.
     *
     * @param pi the index of the current item
     */
    private void downHeapify(int pi) {
        int lci = 2 * pi + 1;
        int rci = 2 * pi + 2;
        int mini = pi;
        if (lci < this.size() && isLarger(this.data.get(lci), this.data.get(mini)) > 0) {

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Guard with `if (!heap.isEmpty()) heap.remove();`.
  2. Bound the drain loop by `for (int i = 0; i < heap.size(); ) heap.remove();` or capture size first.
  3. Wrap remove() in a helper that returns Optional<T> and returns empty when the heap is empty.

Example fix

// before
T top = heap.remove();

// after
T top = heap.isEmpty() ? null : heap.remove();
Defensive patterns

Strategy: validation

Validate before calling

if (!heap.isEmpty()) {
    T top = heap.remove();
}

Try / catch

try {
    T top = heap.remove();
} catch (IllegalStateException e) {
    // heap empty; nothing to remove
}

Prevention

When it happens

Trigger: Calling remove() on a freshly constructed heap with no add() calls; calling remove() more times than elements were added; a drain loop with no bound check.

Common situations: Priority-queue drain loops (`while(true) heap.remove()`); event loops where events are exhausted; test fixtures that forget to populate the heap.

Related errors


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