TheAlgorithms/Java · error · IllegalArgumentException

Input list cannot be null

Error message

Input list cannot be null

What it means

Thrown by the MinHeap(List<HeapElement>) constructor when listElements is null. The constructor iterates the list to seed the heap, so null would NPE; the explicit check yields a clearer message. Unlike MaxHeap's constructor, MinHeap prints a warning ('Null element. Not added to heap') for null ELEMENTS inside a non-null list but still rejects a null list reference.

Source

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

 * HeapElement min = heap.getElement(); // Returns and removes the minimum element
 * ```
 *
 * @author Nicolas Renard
 */
public class MinHeap implements Heap {

    private final List<HeapElement> minHeap;

    /**
     * Constructs a new MinHeap from a list of elements.
     * Null elements in the input list are ignored with a warning message.
     *
     * @param listElements List of HeapElement objects to initialize the heap
     * @throws IllegalArgumentException if the input list is null
     */
    public MinHeap(List<HeapElement> listElements) {
        if (listElements == null) {
            throw new IllegalArgumentException("Input list cannot be null");
        }

        minHeap = new ArrayList<>();

        // Safe initialization: directly add elements first
        for (HeapElement heapElement : listElements) {
            if (heapElement != null) {
                minHeap.add(heapElement);
            } else {
                System.out.println("Null element. Not added to heap");
            }
        }

        // Heapify the array bottom-up
        for (int i = minHeap.size() / 2; i >= 0; i--) {
            heapifyDown(i + 1);
        }

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Pass Collections.emptyList() instead of null when there is nothing to seed.
  2. Guard the caller: `list = list != null ? list : Collections.emptyList()`.
  3. Fix upstream producers to never return null collections.

Example fix

// before
new MinHeap(source.load()); // returns null when empty

// after
List<HeapElement> elems = source.load();
new MinHeap(elems != null ? elems : Collections.emptyList());
Defensive patterns

Strategy: validation

Validate before calling

List<HeapElement> elems = source != null ? source : Collections.emptyList();
new MinHeap(elems);

Prevention

When it happens

Trigger: Passing null directly; passing a factory result that returns null on empty; an uninitialized List field.

Common situations: Repository/query methods returning null instead of an empty list; DI misconfiguration leaving the list unset; conditional initialization skipped.

Related errors


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