来自 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.
应该如何解读?我们可以将空值插入到 LinkedList
中但无法将其插入 Queue
, 尽管实现了 Queue
通过 LinkedList
.
最佳答案
这意味着如果你向一个LinkedList
插入一个null,如果你调用poll
并得到null
,你无法判断是Queue
为空,或者 Queue
的头部有空元素。
因此,您可以将 null
插入到 LinkedList
中,但是如果您打算将该 LinkedList
用作 队列
。
如果你看一下 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
}
关于java - 了解队列插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28147076/