Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding queue insertion

From Javadoc:

Queue implementations generally do not allow insertion of null elements, although some implementations, such as LinkedList, do not prohibit insertion of null. Even in the implementations that permit it, null should not be inserted into a Queue, as null is also used as a special return value by the poll method to indicate that the queue contains no elements.

How should it be interpreted? We can insert the null value into the LinkedList but couldn't insert it into the Queue, despite implementing Queue by LinkedList.

like image 386
St.Antario Avatar asked Jan 26 '15 08:01

St.Antario


Video Answer


2 Answers

It means that if you insert a null to a LinkedList, if you call poll and get null, you can't tell is the Queue is empty or if a null element was at the head of the Queue.

Therefore, you can insert null to a LinkedList, but you should avoid doing so if you intend to use that LinkedList as a Queue.

If you look at the implementation of poll() :

public E poll() {
    if (size==0)
        return null;
    return removeFirst(); // if the first element is null, `removeFirst()`
                          // returns null, and you might mistakenly assume
                          // the Queue is empty
}
like image 89
Eran Avatar answered Sep 24 '22 13:09

Eran


Let me Break it:

  • Queue implementations generally do not allow insertion of null elements

For instance if you take PriorityQueue you can't insert a null value,

 PriorityQueue<String> prQueue=new PriorityQueue<String>();

prQueue.add("aa");
prQueue.add(null);

it will give a NullPointerException.

  • Although some implementations, such as LinkedList, do not prohibit insertion of null

LinkedList also implements Queue but it allow null value. (it says : .. .. generally .. .. not restricted )

LinkedList<String> linkdeList=new LinkedList<String>();

linkdeList.add("aa");
linkdeList.add(null); //ok.
  • Even in the implementations that permit it, null should not be inserted into a Queue, as null is also used as a special return value by the poll method to indicate that the queue contains no elements.

So you can insert null in LinkedList but you shouldn't specially if you use LinkedList as a queue Because poll() method of LinkedList

Returns:
the head of this list, or null if this list is empty

so if you insert null and get null from poll() you can't say is it your inserted one or the LinkedList is empty.

like image 31
Saif Avatar answered Sep 26 '22 13:09

Saif