TheAlgorithms/Java · error · IllegalArgumentException

Cannot insert null element

Error message

Cannot insert null element

What it means

Thrown by MinHeap.insertElement(HeapElement) when the passed element is null. The heap stores HeapElement objects and calls toggleUp which dereferences element.getKey(), so a null would NPE later. The library fails fast with IllegalArgumentException to surface the caller bug at the source.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java:213

     * @return HeapElement with the lowest key
     * @throws EmptyHeapException if the heap is empty
     */
    private HeapElement extractMin() throws EmptyHeapException {
        if (minHeap.isEmpty()) {
            throw new EmptyHeapException("Cannot extract from empty heap");
        }
        HeapElement result = minHeap.getFirst();
        deleteElement(1);
        return result;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void insertElement(HeapElement element) {
        if (element == null) {
            throw new IllegalArgumentException("Cannot insert null element");
        }
        minHeap.add(element);
        toggleUp(minHeap.size());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void deleteElement(int elementIndex) throws EmptyHeapException {
        if (minHeap.isEmpty()) {
            throw new EmptyHeapException("Cannot delete from empty heap");
        }
        if ((elementIndex > minHeap.size()) || (elementIndex <= 0)) {
            throw new IndexOutOfBoundsException("Index " + elementIndex + " is out of heap range [1, " + minHeap.size() + "]");
        }

        // Replace with last element and remove last position

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Filter nulls before inserting: `elements.stream().filter(Objects::nonNull).forEach(heap::insertElement)`.
  2. Wrap the insert in a null check at the call site.
  3. Audit upstream data sources that feed the heap to eliminate null production.
  4. Return a sentinel HeapElement instead of null from your factory.

Example fix

// before
heap.insertElement(map.get(missingKey)); // returns null

// after
HeapElement e = map.get(key);
if (e != null) {
    heap.insertElement(e);
}
Defensive patterns

Strategy: validation

Validate before calling

if (element != null) {
    heap.insertElement(element);
}

Try / catch

try {
    heap.insertElement(element);
} catch (IllegalArgumentException e) {
    // element was null — filter upstream instead
}

Prevention

When it happens

Trigger: Passing null to insertElement. Inserting the result of a factory/map lookup that returned null because a key was absent. Inserting from a stream that contains null elements.

Common situations: Optional.get() on an empty Optional before insert. Map.get(key) returning null for a missing key, then inserted. Deserialization producing null fields when source data is incomplete.

Related errors


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