Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ความแตกต่างระหว่าง peek(), poll() และ remove() ของ Queue Interface ใน Java

Queue แทนคอลเลกชันที่ตั้งใจจะเก็บข้อมูลก่อนประมวลผล เป็นการจัดเรียงแบบ First-In-First-Out (FIFO) องค์ประกอบแรกที่ใส่เข้า queue คือองค์ประกอบแรกที่ถูกนำออก

เมธอด peek()

เมธอดนี้คืนค่าอ็อบเจกต์ที่ด้านบนของ queue ปัจจุบัน โดยไม่ลบมันออก หาก queue ว่าง เมธอดนี้คืนค่า 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()

เมธอด poll() ของอินเทอร์เฟซ Queue คืนค่าอ็อบเจกต์ที่ด้านบนของ queue ปัจจุบัน และลบมันออก หาก queue ว่าง เมธอดนี้คืนค่า 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

เมธอด remove()

เมธอด remove() คล้ายกับ poll() แต่หาก queue ว่าง จะโยน NoSuchElementException แทนที่จะคืนค่า 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.remove());
        
        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