Java 中 Queue 介面的 peek()、poll() 和 remove() 方法之間的區別是什麼?
這表示一個在處理前儲存資料的集合。這種安排的型別遵循先進先出 (FIFO) 的原則。放入佇列的第一個元素,也將會是第一個取出的元素。
peek() 方法
peek() 方法返回當前佇列頂部的物件,而不會將其移除。如果佇列為空,則此方法返回 null。
示例
import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; public class QueueExample { public static void main(String args[]) { Queue<String> queue = new LinkedList<String>(); queue.add("Java"); queue.add("JavaFX"); queue.add("OpenCV"); queue.add("Coffee Script"); queue.add("HBase"); System.out.println("Element at the top of the queue: "+queue.peek()); Iterator<String> it = queue.iterator(); System.out.println("Contents of the queue: "); while(it.hasNext()) { System.out.println(it.next()); } } }
輸出
Element at the top of the queue: Java Contents of the queue: Java JavaFX OpenCV Coffee Script Hbase
poll() 方法
Queue 介面的 poll() 方法返回當前佇列頂部的物件,並將其移除。如果佇列為空,則此方法返回 null。
示例
import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; public class QueueExample { public static void main(String args[]) { Queue<String> queue = new LinkedList<String>(); queue.add("Java"); queue.add("JavaFX"); queue.add("OpenCV"); queue.add("Coffee Script"); queue.add("HBase"); System.out.println("Element at the top of the queue: "+queue.poll()); Iterator<String> it = queue.iterator(); System.out.println("Contents of the queue: "); while(it.hasNext()) { System.out.println(it.next()); } } }
輸出
Element at the top of the queue: Java Contents of the queue: JavaFX OpenCV Coffee Script HBase
廣告