使用 Queue
Queues 按加入的先后顺序收集并返回对象。队列还具有容量限制。本练习中,您将创建一个等待名单 Queue(具体使用 ArrayBlockingQueue),并向其中添加姓名。您还将看到当添加的姓名超过容量限制时会发生什么。
本练习是课程的一部分
Java 的数据类型与异常
练习说明
- 在应用中导入
ArrayBlockingQueue。 - 构造一个容量为 3 的
String类型ArrayBlockingQueue,并将变量waitList指向它。 - 向
waitList添加一个新姓名:"Tarah"。 - 从
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);
}
}