// Queue in Java using LinkedList
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
// Create a queue object
Queue<Integer> queue = new LinkedList<>();
// Add elements to the queue
queue.add(1);
queue.add(2);
queue.add(3);
// Display the queue
System.out.println("Queue: " + queue);
// Remove an element from the queue (FIFO)
int removedElement = queue.remove();
System.out.println("Removed element: " + removedElement);
// Display the queue after removal
System.out.println("Queue after removal: " + queue);
// Peek at the front element of the queue
int frontElement = queue.peek();
System.out.println("Front element: " + frontElement);
// Check if the queue is empty
boolean isEmpty = queue.isEmpty();
System.out.println("Is the queue empty? " + isEmpty);
}
}
Queue 是 Java 集合框架中的一个接口,表示队列。队列是一种遵循 FIFO(先进先出)原则的数据结构。LinkedList 类来实现 Queue 接口。LinkedList 实现了 Queue 接口,并且提供了高效的插入和删除操作。希望这段代码和解释能帮助你理解如何在 Java 中使用队列。
下一篇:java 随机
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站