import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
// 创建一个队列
Queue<String> queue = new LinkedList<>();
// 添加元素到队列 (入队)
queue.offer("Apple");
queue.offer("Banana");
queue.offer("Orange");
// 打印队列中的元素
System.out.println("Queue: " + queue);
// 移除并返回队列头部的元素 (出队)
String element = queue.poll();
System.out.println("Removed element: " + element);
// 查看队列头部的元素,但不移除它
String headElement = queue.peek();
System.out.println("Head element: " + headElement);
// 检查队列是否为空
if (queue.isEmpty()) {
System.out.println("Queue is empty.");
} else {
System.out.println("Queue is not empty.");
}
}
}
LinkedList
实现 Queue
接口来创建一个队列。offer()
方法将元素添加到队列的末尾(入队)。poll()
方法移除并返回队列头部的元素(出队)。如果队列为空,则返回 null
。peek()
方法查看队列头部的元素,但不移除它。如果队列为空,则返回 null
。isEmpty()
方法检查队列是否为空。通过这些操作,可以实现常见的队列使用场景,如任务调度、消息队列等。
上一篇:java单元测试工具
下一篇:java set 交集
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站