Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Khác biệt giữa peek(), poll() và remove() của interface Queue trong Java


Queue là collection kiểu First-In-First-Out (FIFO). Phần tử đầu tiên vào là phần tử đầu tiên ra.

Phương thức peek()

Trả về object ở đầu queue mà không xóa. Nếu queue rỗng trả null.

Ví dụ

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());       }    } }

Kết quả

Element at the top of the queue: Java Contents of the queue: Java JavaFX OpenCV Coffee Script Hbase

Phương thức poll()

poll() trả về object ở đầu queue và xóa nó. Nếu queue rỗng trả null.

Ví dụ

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());       }    } }

Kết quả

Element at the top of the queue: Java Contents of the queue: JavaFX OpenCV Coffee Script HBase