天天看點

java 隊列 remove,在 Queue 中 poll()和 remove()有什麼差別

java面試

在 Queue 中 poll()和 remove()有什麼差別

相同點:都是傳回第一個元素,并在隊列中删除傳回的對象。

不同點:如果沒有元素 poll()會傳回 null,而 remove()會直接抛出 NoSuchElementException 異常。

Queue-poll

public static void main(String[] args) {

Queue queue = new LinkedList();

queue.offer("string"); // add

System.out.println(queue.poll());

System.out.println(queue.poll());

System.out.println(queue.size());

}

傳回

string

null

Queue-remove

用remove時

public static void main(String[] args) {

Queue queue = new LinkedList();

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)