Before you try to find duplicate question or downvotes, please let me explain 🙂
I think I read most of stackoverflow answers on this topic. They all summarize to this:
Null should not be inserted into a Queue, as null is also used as a special return value by some methods to indicate that the queue contains no elements.
They are totally right (let’s ignore LinkedList
here). If I were to call for example queue.poll()
or queue.peek()
and return type is null, I wouldn’t know if that null represents null as element or null as no elements.
But any programmer with basic knowledge can do something like this to avoid given problem:
//queue initialization.. queue.add(null); if (!queue.isEmpty()){ System.out.println(queue.poll()); }
So I must ask again. Was “null as special return type” only reason why it is ‘banned’ in mostly Queue
implementations(except LinkedList
)? Or I am missing something additional concerning this situation?
Advertisement
Answer
The queue implementations could have been designed to permit null entries, but they were not. This is a design tradeoff: the ‘flexibility’ of being able to insert null entries, versus the cumbersome programming interface of having to check whether the queue contains any elements before you can call a method that is there in part to determine whether the queue contains any elements.
The clue is in the name ‘poll’. If poll is not able to perform a ‘remove and return; else indicate nothing to return’, then poll is not a useful method; a test for empty, followed by the existing ‘remove’ call, does the job.
I suppose, therefore, that the queue designers had in mind a queue that contained ‘things’ rather than the absence of things (i.e., they took the word literally) and accepted that restriction for the convenience of a single-method poll call.
In short, your answer (IMO) is ‘yes, that is the reason’, but I think the reason is a good one.