TheAlgorithms/Java · error · IllegalArgumentException

Cannot insert null element

Error message

Cannot insert null element

What it means

Thrown by MaxHeap.insertElement(HeapElement) when the element is null. Heap ordering relies on HeapElement.getKey() during toggleUp, which would NPE on null; the explicit guard gives a clear message. Null elements are not silently skipped by insert (unlike in the constructor).

Source

Thrown at src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java:190

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

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

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

        // Replace with last element and remove last position

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Null-check the element before calling insertElement and skip or substitute.
  2. Fix the upstream producer to never yield null HeapElements.
  3. Filter nulls out of any bulk-insert flow before iterating into insertElement.

Example fix

// before
heap.insertElement(element);

// after
if (element != null) {
    heap.insertElement(element);
}
Defensive patterns

Strategy: type-guard

Validate before calling

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

Type guard

// No compile-time nullable guard in Java; use explicit null check or Optional.
Optional.ofNullable(element).ifPresent(heap::insertElement);

Prevention

When it happens

Trigger: Calling insertElement(null); passing a HeapElement from a lookup that returned null; reading elements from a stream/source that yields null slots.

Common situations: Optional-empty lookups forwarded directly; deserialization producing null; conditional construction that leaves the element null.

Related errors


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