操作 Queue
Queues 會依照加入的先後順序收集並取出物件。Queues 也有容量限制。這裡你要建立一個等候名單的 Queue(具體使用 ArrayBlockingQueue),並把姓名加入其中。你也會看到當嘗試加入的姓名超過容量上限時會發生什麼事。
本練習屬於課程
Java 的資料型別與例外狀況
練習說明
- 匯入要在應用程式中使用的
ArrayBlockingQueue。 - 建立一個容量為 3 的
String型別ArrayBlockingQueue,並指定給變數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);
}
}