TheAlgorithms/Java · error · NoSuchElementException

Deque is empty

Error message

Deque is empty

What it means

Thrown by Deque.pollFirst() as a NoSuchElementException when head == null, i.e. the doubly-linked deque holds no nodes. Unlike java.util.Deque.pollFirst (which returns null on empty), this implementation throws, so callers cannot rely on the standard-library convention of a null return.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/queues/Deque.java:79

            head = newNode;
            tail = newNode;
        } else {
            newNode.prev = tail;
            tail.next = newNode;
            tail = newNode;
        }
        size++;
    }

    /**
     * Removes and returns the first (head) value in the deque
     *
     * @return the value of the head of the deque
     * @throws NoSuchElementException if the deque is empty
     */
    public T pollFirst() {
        if (head == null) {
            throw new NoSuchElementException("Deque is empty");
        }

        T oldHeadVal = head.val;
        if (head == tail) {
            head = null;
            tail = null;
        } else {
            head = head.next;
            head.prev = null;
        }
        size--;
        return oldHeadVal;
    }

    /**
     * Removes and returns the last (tail) value in the deque
     *
     * @return the value of the tail of the deque

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Check the public size field or isEmpty()/head==null state before calling pollFirst().
  2. Loop while deque.size > 0 (or a custom isEmpty) instead of relying on a null sentinel.
  3. Catch NoSuchElementException when an empty deque is a legitimate control-flow outcome.

Example fix

// before
T v = deque.pollFirst(); // throws, NOT null like java.util.Deque

// after
T v = (deque.size > 0) ? deque.pollFirst() : null;
Defensive patterns

Strategy: validation

Validate before calling

T v = (deque.size > 0) ? deque.pollFirst() : null;

Type guard

// narrow: distinguish this throwing Deque from the JDK Deque whose poll returns null
boolean canPollFirst = deque.size > 0;

Try / catch

null

Prevention

When it happens

Trigger: Calling pollFirst() on a newly constructed Deque, or calling pollFirst() until size reaches zero and then calling it once more. Any removal beyond the node count triggers it.

Common situations: Assuming this Deque behaves like java.util.ArrayDeque/LinkedList whose poll methods return null on empty; draining a deque in a while loop without an emptiness condition; using pollFirst as the sole loop-exit signal.

Related errors


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