Course contentsShow
← Java
Lesson 1210 of 2,87027. Queue and Deque ImplementationsFree lesson

Null Elements Forbidden and Iteration Order

Why ArrayDeque prohibits null elements and how iteration proceeds from head to tail.

Null Elements Forbidden and Iteration Order

What you'll learn: Why ArrayDeque doesn't allow null elements and how iteration moves through the deque.

Why No Nulls?

Unlike LinkedList, ArrayDeque forbids null elements entirely. If you try to add null, it throws a NullPointerException. Why this restriction?

The reason is sentinel values. ArrayDeque uses null internally to detect empty slots in its circular array. Methods like poll() return null to signal "the deque is empty." If you could store null as a legitimate element, there'd be no way to distinguish between "this slot is empty" and "this slot contains null."

Think of it like a parking lot system where an empty space is marked with a flag. If cars could also carry identical flags, you couldn't tell which spaces were truly vacant!

Iteration Order: Head to Tail

When you iterate over an ArrayDeque using a standard iterator or enhanced for-loop, you traverse from head to tail — the same order you'd encounter elements if you kept calling removeFirst().

ArrayDeque<String> deque = new ArrayDeque<>();
deque.addLast("A");
deque.addLast("B");
deque.addFirst("Z");

for (String s : deque) {
    System.out.println(s);
}
// Output: Z, A, B  (head to tail)

The iteration starts at the head (where removeFirst() would remove from) and proceeds toward the tail. This is true even though internally the elements might wrap around in the circular buffer — the iterator handles that complexity for you.

For reverse iteration, you can use descendingIterator() to go from tail to head.

Key Takeaway: ArrayDeque prohibits null elements because it uses null as an internal sentinel value to mark empty positions; iteration always proceeds from head to tail, matching the FIFO order of removeFirst() calls.