TheAlgorithms/Java · error · IllegalArgumentException
Cannot enqueue null data
Error message
Cannot enqueue null data
What it means
Thrown by LinkedQueue.enqueue(T) as an IllegalArgumentException when the argument is null. This unbounded linked-list queue explicitly forbids null elements to disambiguate them from the empty-queue sentinel and to keep dequeue()'s return semantics unambiguous.
Source
Thrown at src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java:51
/**
* Checks if the queue is empty.
*
* @return true if the queue is empty, otherwise false.
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Adds an element to the rear of the queue.
*
* @param data the element to insert.
* @throws IllegalArgumentException if data is null.
*/
public void enqueue(T data) {
if (data == null) {
throw new IllegalArgumentException("Cannot enqueue null data");
}
Node<T> newNode = new Node<>(data);
if (isEmpty()) {
front = newNode;
} else {
rear.next = newNode;
}
rear = newNode;
size++;
}
/**
* Removes and returns the element at the front of the queue.
*
* @return the element at the front of the queue.
* @throws NoSuchElementException if the queue is empty.View on GitHub (pinned to fdfb9a395b)
Solutions
- Null-check or use a default before enqueue: if (data != null) queue.enqueue(data).
- Filter nulls at the source (e.g. Stream.filter(Objects::nonNull)) before they reach the queue.
- Replace missing values with a sentinel/empty representation instead of null.
Example fix
// before
queue.enqueue(map.get(key)); // get may return null
// after
String v = map.get(key);
if (v != null) {
queue.enqueue(v);
} Defensive patterns
Strategy: validation
Validate before calling
if (data != null) {
queue.enqueue(data);
} Type guard
java.util.Objects.nonNull(data)
Try / catch
null
Prevention
- Filter nulls at the data source before they reach enqueue.
- Use Objects.requireNonNull(data, "...") at the boundary to fail with your own message.
- Avoid Optional.orElse(null) directly feeding the queue.
When it happens
Trigger: Passing a literal null to enqueue(), or passing an uninitialized field/map-lookup/Optional.orElse(null) result that evaluates to null. Any code path that fails to initialize a value before enqueuing it triggers the guard.
Common situations: Map.get() returning null for a missing key then enqueued; JSON/DB deserialization yielding null fields; default initial values that never got assigned; refactoring that removed an assignment but left the enqueue call.
Related errors
- Cannot enqueue null item.
- Queue capacity must be greater than 0
- Capacity must be greater than zero.
- Cannot insert null element
- Cannot add null element to the list
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/15f0f53e4bc05c8c.
Report an issue: GitHub.