การใช้งาน Queue
Queue เก็บและคืนออบเจกต์ตามลำดับที่เพิ่มเข้ามา และยังมีความจุสูงสุดอีกด้วย ในแบบฝึกหัดนี้ จะสร้าง Queue สำหรับรายชื่อผู้รอ (โดยใช้ ArrayBlockingQueue) แล้วเพิ่มชื่อเข้าไป พร้อมสังเกตว่าเกิดอะไรขึ้นเมื่อพยายามเพิ่มชื่อเกินกว่าความจุที่กำหนด
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
ชนิดข้อมูลและการจัดการข้อยกเว้นใน Java
คำแนะนำการฝึกหัด
- Import
ArrayBlockingQueueเพื่อใช้งานในแอปพลิเคชัน - สร้าง
ArrayBlockingQueueของStringใหม่ที่มีความจุ 3 แล้วกำหนดให้กับตัวแปรwaitList - เพิ่มชื่อใหม่
"Tarah"เข้าไปในwaitList - นำชื่อแรกออกจาก
waitList
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
// Import ArrayBlockingQueue
import java.util.____.____;
public class GetInLine {
public static void main(String[] args) {
// Create an ArrayBlockingQueue of up to 3 names using parameterized constructor
____<____> waitList = new ____<____>(____);
waitList.offer("Sally");
waitList.offer("Benny");
// Add the name "Tarah"
waitList.____(____);
System.out.println(waitList);
waitList.offer("Letty");
System.out.println(waitList);
// Remove the first name
String first = waitList.____();
System.out.println(first);
waitList.offer("Letty");
System.out.println(waitList);
}
}