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 CircularDoublyLinkedList.append(E) when value is null. The list links nodes bidirectionally through head.prev/head.next and assumes non-null payloads. The library rejects null with NullPointerException to keep node-walking and equality semantics sound.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/lists/CircularDoublyLinkedList.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");
        }
        Node<E> newNode = new Node<>(value, head, head.prev);
        head.prev.next = newNode;
        head.prev = newNode;
        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() {
        if (size == 0) {
            return "[]";
        }

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Filter nulls before appending: `coll.stream().filter(Objects::nonNull).forEach(list::append)`.
  2. Null-check at the call site.
  3. Replace nullable sources with Optional and skip on empty.
  4. Document and enforce non-null contracts upstream.

Example fix

// before
list.append(value); // value may be null

// after
if (value != null) {
    list.append(value);
}
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). Inserting values from a stream or collection that may contain null. Appending the result of a nullable getter.

Common situations: Deserialized objects with optional fields. Map lookups returning null for absent keys. APIs that return null on failure piped directly into append.

Related errors


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