TheAlgorithms/Java · error · NullPointerException
Element cannot be null
Error message
Element cannot be null
What it means
Thrown by CursorLinkedList.indexOf(T) when element is null. The method iterates logical nodes calling iterator.element.equals(element), so a null element would NPE on the equals call. The library rejects null upfront with NullPointerException.
Source
Thrown at src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java:77
int start = head;
while (start != -1) {
T element = cursorSpace[start].element;
System.out.println(element.toString());
start = cursorSpace[start].next;
}
}
}
/**
* Finds the logical index of a specified element in the list.
*
* @param element the element to search for in the list
* @return the logical index of the element, or -1 if not found
* @throws NullPointerException if element is null
*/
public int indexOf(T element) {
if (element == null) {
throw new NullPointerException("Element cannot be null");
}
try {
Objects.requireNonNull(element);
Node<T> iterator = cursorSpace[head];
for (int i = 0; i < count; i++) {
if (iterator.element.equals(element)) {
return i;
}
iterator = cursorSpace[iterator.next];
}
} catch (Exception e) {
return -1;
}
return -1;
}
/**
* Retrieves an element at a specified logical index in the list.View on GitHub (pinned to fdfb9a395b)
Solutions
- Null-check before calling indexOf.
- Wrap the element in Optional and skip the search when empty.
- Filter null values out of the data feeding the list and its queries.
- Return -1 yourself when the input is null rather than calling indexOf.
Example fix
// before int idx = list.indexOf(map.get(key)); // after T e = map.get(key); int idx = (e == null) ? -1 : list.indexOf(e);
Defensive patterns
Strategy: validation
Validate before calling
if (element != null) {
return list.indexOf(element);
}
return -1; Try / catch
try {
return list.indexOf(element);
} catch (NullPointerException e) {
return -1;
} Prevention
- Null-check before indexOf, returning -1 yourself for null input.
- Filter nulls from query sources.
- Prefer Optional for values that may be absent.
When it happens
Trigger: Calling indexOf(null). Searching for an element obtained from a nullable source. Passing the result of Map.get on a missing key.
Common situations: User input that was not null-validated. Optional.orElse(null) fed to indexOf. Lookup tables that return null for absent entries.
Related errors
- Cannot add null element to the list
- Cannot add null element to the list
- Input lists must not be null.
- Cannot insert null element
- Input lists and result collection must not be null.
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/27c135406993087b.
Report an issue: GitHub.