Why null values are not allowed in ArrayDeque?

From the Javadoc for Deque:

While Deque implementations are not strictly required to prohibit the insertion of null elements, they are strongly encouraged to do so. Users of any Deque implementations that do allow null elements are strongly encouraged not to take advantage of the ability to insert nulls. This is so because null is used as a special return value by various methods to indicated that the deque is empty.

The ArrayDeque implementation also uses null to indicate an empty element (as explained in sestus' and Aman jangra's answers), so the reasoning is two-fold: contract and implementation details.

It's worth noting that it ArrayDeque could easily support null elements without much additional complexity, so the more compelling reason seems to be the suggestion of the Deque interface.


The first answer is right on (implementation uses null to indicate an empty element). I also wanted to point out that you can always insert an element that represents null -- something like this:

private static final String NULL_INDICATOR = "_NULL_";

private final Deque<String> elementDeque = new ArrayDeque<>();

public final pushElement(String element) {
  if (element == null) {
    element = NULL_INDICATOR;
  }

  elementDeque.push(element);
}

public final peekElement() {
  String element = elementDeque.peek();

  return NULL_INDICATOR.equals(element) ? null : element;
}

public final popElement() {
  elementDeque.pop();
}

Workaround: ArrayDeque<Optional<T>> (java.util.Optional)

// Add non-null value
queue.add(Optional.of(value))

// Add nullable value
queue.add(Optional.ofNullable(value))

// Add null
queue.add(Optional.empty())

// Unbox
last = queue.pollLast().orElse(null)

This may be so because null is used as a special return value by various methods to indicate that the deque is empty.However not all deques prohibit insertion of null values.

Tags:

Java