29 在 Queue 中 poll()和 remove()有什么区别?

在 Queue 中 poll()和 remove()有什么区别?

答:

  • 队列(queue)是一个典型的先进先出(FIFO)的容器。即从容器的一端放入事物,从另一端取出,并且事物放入容器的顺序与取出的顺序是相同的。

相同点:

  • 都是返回第一个元素,并在队列中删除返回的对象。

不同点:

  • remove() ,如果队列为空的时候,则会抛出异常

  • 而poll()只会返回null
     

参考博文: https://www.baidu.com/link?url=SnhZXx9Ub8vuSKt-vuYTI75AdqLgusyRcptOMptbqLXQ86E0D7MXWpl5-Y2MzS9L&wd=&eqid=a86b6dfe000995cd000000065e9bb0b7
 

Queue-poll代码示例:

Queue<String> queue = new LinkedList<String>();
queue. offer("string"); // add
System. out. println(queue. poll());
System. out. println(queue. remove());
System. out. println(queue. size());

 

返回

string
null
0

 

Queue-remove代码示例

    public static void main(String[] args) {
        Queue<String> queue = new LinkedList<String>();
        queue.offer("string"); // add
        System.out.println(queue.poll());
        System.out.println(queue.remove());
        System.out.println(queue.size());
    }

 

报NoSuchElementException的异常

Exception in thread "main" string
java.util.NoSuchElementException
    at java.util.LinkedList.removeFirst(LinkedList.java:270)
    at java.util.LinkedList.remove(LinkedList.java:685)
    at mytest.Mytest.main(Mytest.java:20)

 

原文地址:https://www.cnblogs.com/ynzj123/p/12730356.html