了解队列插入

Understanding queue insertion

来自 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,但我们可以将空值插入 LinkedList 但无法将其插入 Queue

意思是如果你给LinkedList插入一个null,如果你调用poll得到null,你分不清是Queue空元素或空元素位于 Queue.

的开头

因此,您可以将 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
}

让我打破它:

  • 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.

所以你可以在 LinkedList 中插入 null 但如果你使用 LinkedList 作为队列你不应该特别 因为 poll() 方法 LinkedList

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

所以如果你插入 null 并从 poll() 得到 null 你不能说它是你插入的还是 LinkedList 是空的。