TheAlgorithms/Java · error · IllegalArgumentException

Cannot insert null into the heap.

Error message

Cannot insert null into the heap.

What it means

Thrown by GenericHeap.add(T) when item is null. The heap maintains a HashMap<T,Integer> index and relies on Comparable ordering during upHeapify, both of which break on null (compareTo would NPE and the map cannot key null safely). Rejecting null at the boundary gives a clear message instead of a later NullPointerException.

Source

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

/**
 * A generic implementation of a max heap data structure.
 *
 * @param <T> the type of elements in this heap, must extend Comparable.
 */
public class GenericHeap<T extends Comparable<T>> {

    private final ArrayList<T> data = new ArrayList<>();
    private final HashMap<T, Integer> map = new HashMap<>();

    /**
     * Adds an item to the heap, maintaining the heap property.
     *
     * @param item the item to be added
     */
    public void add(T item) {
        if (item == null) {
            throw new IllegalArgumentException("Cannot insert null into the heap.");
        }

        this.data.add(item);
        map.put(item, this.data.size() - 1);
        upHeapify(this.data.size() - 1);
    }

    /**
     * Restores the heap property by moving the item at the given index upwards.
     *
     * @param ci the index of the current item
     */
    private void upHeapify(int ci) {
        int pi = (ci - 1) / 2;
        if (ci > 0 && isLarger(this.data.get(ci), this.data.get(pi)) > 0) {
            swap(pi, ci);
            upHeapify(pi);
        }

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Filter nulls out of the source collection before adding each element.
  2. Replace null with a meaningful default/sentinel value, or skip the element conditionally.
  3. Fix the upstream producer so it never emits null (return Optional and handle absence explicitly).

Example fix

// before
heap.add(map.get(maybeMissingKey));

// after
T v = map.get(maybeMissingKey);
if (v != null) heap.add(v);
Defensive patterns

Strategy: type-guard

Validate before calling

T item = produceItem();
if (item != null) {
    heap.add(item);
}

Type guard

// Java has no type guard for nullability at compile time; use explicit null check.
// If using Optional:
Optional<T> opt = Optional.ofNullable(produceItem());
opt.ifPresent(heap::add);

Prevention

When it happens

Trigger: Calling add(null) directly; passing the result of Map.get(key) that returned null; iterating a collection that contains null elements and forwarding them to add().

Common situations: Uninitialized fields defaulting to null; Optional.orElse(null) piped into the heap; deserialization or JSON parsing that yields null slots.

Related errors


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