TheAlgorithms/Java · error · IllegalArgumentException
Input list cannot be null
Error message
Input list cannot be null
What it means
Thrown by the MaxHeap(List<HeapElement>) constructor when listElements is null. The constructor iterates the list to build the heap, so a null reference would NPE; the explicit check produces a clearer error. Note null ELEMENTS inside a non-null list are silently skipped (not an error).
Source
Thrown at src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java:43
* </pre>
*
* @author Nicolas Renard
*/
public class MaxHeap implements Heap {
/** The internal list that stores heap elements */
private final List<HeapElement> maxHeap;
/**
* Constructs a new MaxHeap from a list of elements.
* Null elements in the input list are ignored.
*
* @param listElements List of HeapElement objects to initialize the heap
* @throws IllegalArgumentException if the input list is null
*/
public MaxHeap(List<HeapElement> listElements) {
if (listElements == null) {
throw new IllegalArgumentException("Input list cannot be null");
}
maxHeap = new ArrayList<>();
// Safe initialization: directly add non-null elements first
for (HeapElement heapElement : listElements) {
if (heapElement != null) {
maxHeap.add(heapElement);
}
}
// Heapify the array bottom-up
for (int i = maxHeap.size() / 2; i >= 0; i--) {
heapifyDown(i + 1); // +1 because heapifyDown expects 1-based index
}
}
/**View on GitHub (pinned to fdfb9a395b)
Solutions
- Pass an empty list (Collections.emptyList()) instead of null when there is nothing to seed.
- Guard the caller with a null check and default to an empty list.
- Fix the upstream producer to never return null collections.
Example fix
// before new MaxHeap(repository.findAll()); // returns null when empty // after List<HeapElement> elems = repository.findAll(); new MaxHeap(elems != null ? elems : Collections.emptyList());
Defensive patterns
Strategy: validation
Validate before calling
List<HeapElement> elems = source != null ? source : Collections.emptyList(); new MaxHeap(elems);
Prevention
- Never pass null where a collection is expected; use Collections.emptyList().
- Fix producers (repositories, queries) to return empty lists, not null.
- Annotate parameters @Nonnull and enable null-analysis.
When it happens
Trigger: Passing null directly; passing the result of a factory/method that returns null on empty input; an uninitialized List field defaulting to null.
Common situations: DI/bean wiring that fails to inject the list; a repository/query method returning null instead of an empty list; conditional initialization that leaves the field null.
Related errors
- Cannot insert null element
- Input list cannot be null
- Cannot insert null into the heap.
- initialCapacity < 1
- Index ${elementIndex} is out of heap range [1, ${maxHeap.siz
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/eec4cee37bc51dc6.
Report an issue: GitHub.