/*
* 在 Queue 中 poll()和 remove() 的区别
*/
public static void pollDefRemove(){
/*
* 相同点:都是返回第一个元素,并在队列中删除返回的对象。
* 不同点:如果没有元素 poll()会返回 null,而 remove()会直接抛出 NoSuchElementException 异常。
*/
Queue<String> queue = new LinkedList<String>();
//添加
queue.add("aa");
queue.offer("abc");
queue.offer("def");
System.out.println(queue);
System.out.println(queue.poll());
System.out.println(queue);
try {
System.out.println(queue.remove());
} catch (NoSuchElementException e){
System.out.println("queue.remove() --> 【没有元素】");
}
System.out.println(queue);
System.out.println(queue.size());
}
【在 Queue 中 poll()和 remove() 的区别】
于 2022-06-21 09:50:51 首次发布