Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why null values are not allowed in ArrayDeque?

Tags:

java

I know Hashtable doesn't allow null values as it was legacy, which was fixed by HashMap. Null is not allowed in a tree as sorting would be an issue. But why us null not allowed in ArrayDeque?

like image 675
Muthu Avatar asked Jan 18 '16 09:01

Muthu


People also ask

Does ArrayDeque allow null?

Null elements are prohibited in the ArrayDeque. ArrayDeque class is likely to be faster than Stack when used as a stack.

Can we add null in ArrayDeque Java?

Null elements are prohibited. This class is likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue. Most ArrayDeque operations run in amortized constant time. Exceptions include remove , removeFirstOccurrence , removeLastOccurrence , contains , iterator.

Can queue have null values?

Queue implementations generally do not allow insertion of null elements, although some implementations, such as LinkedList , do not prohibit insertion of null.

Which collection does not allow null value?

Hashtable does not allow any null as key or value, and Hashtable is legacy and only single thread can access at a time.


2 Answers

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.

like image 61
Kayaman Avatar answered Sep 23 '22 13:09

Kayaman


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.

like image 24
Aman jangra Avatar answered Sep 20 '22 13:09

Aman jangra