来自Javadoc:
队列实现通常不允许插入null 虽然某些实现(如LinkedList)不这样做 禁止插入null。即使在允许的实现中 它, null不应该插入到队列中,因为null也被用作 poll方法的特殊返回值表示队列 不包含任何元素。
应如何解释?我们可以将空值插入LinkedList
,但无法将其插入Queue
,尽管Queue
实施了LinkedList
。
答案 0 :(得分:7)
这意味着如果您向LinkedList
插入空值,如果您拨打poll
并获取null
,则无法告诉Queue
是Queue
如果null元素位于null
的顶部。
因此,您可以将LinkedList
插入LinkedList
,但如果您打算将Queue
用作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
}
的实现:
{{1}}
答案 1 :(得分:2)
让我打破它:
Queue implementations generally do not allow insertion of null elements
例如,如果您使用PriorityQueue
,则无法插入空值,
PriorityQueue<String> prQueue=new PriorityQueue<String>();
prQueue.add("aa");
prQueue.add(null);
它会给出NullPointerException
。
Although some implementations, such as LinkedList, do not prohibit insertion of null
LinkedList
也实现Queue
但它允许空值。 (它说:.. .. 一般 .. ..不受限制)
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.
因此,您可以在null
中插入LinkedList
,但如果您使用LinkedList作为队列,则不应该特别
因为poll()
LinkedList
方法
Returns:
the head of this list, or null if this list is empty
因此,如果您从null
插入null
并获取poll()
,则无法说明是您插入的,还是LinkedList
为空。