TheAlgorithms/Java · error · NullPointerException

Cannot add null element to the list

Error message

Cannot add null element to the list

What it means

Thrown by CircleLinkedList.append(E) when value is null. The list stores Node<E> wrappers and the circular structure assumes non-null payloads for traversal equality. The library rejects null explicitly with NullPointerException rather than allowing a null to corrupt iteration semantics.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java:64

    /**
     * Returns the current size of the list.
     *
     * @return the number of elements in the list
     */
    public int getSize() {
        return size;
    }

    /**
     * Appends a new element to the end of the list. Throws a NullPointerException if
     * a null value is provided.
     *
     * @param value the value to append to the list
     * @throws NullPointerException if the value is null
     */
    public void append(E value) {
        if (value == null) {
            throw new NullPointerException("Cannot add null element to the list");
        }
        if (tail == null) {
            tail = new Node<>(value, head);
            head.next = tail;
        } else {
            tail.next = new Node<>(value, head);
            tail = tail.next;
        }
        size++;
    }

    /**
     * Returns a string representation of the list in the format "[ element1, element2, ... ]".
     * An empty list is represented as "[]".
     *
     * @return the string representation of the list
     */
    public String toString() {

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Filter nulls from the source collection before appending.
  2. Add a null check at the call site before append.
  3. Use Optional and skip append on empty.
  4. Normalize upstream to never produce nulls.

Example fix

// before
list.append(map.get(key)); // null when absent

// after
E v = map.get(key);
if (v != null) list.append(v);
Defensive patterns

Strategy: validation

Validate before calling

if (value != null) {
    list.append(value);
}

Try / catch

try {
    list.append(value);
} catch (NullPointerException e) {
    // value was null — filter upstream
}

Prevention

When it happens

Trigger: Calling append(null). Appending the result of a lookup that returned null. Appending from a collection that permits nulls.

Common situations: Map.get on a missing key. Optional.orElse(null) piped into append. Third-party data with nullable fields inserted without filtering.

Related errors


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