Java Queue 接口
提示
- 队列接口定义:
Queue
接口提供队列数据结构功能,扩展自Collection
接口。 - 实现类:主要通过
ArrayDeque
、LinkedList
和PriorityQueue
类实现。 - 主要操作:支持队列操作如
add()
、offer()
、peek()
、poll()
,遵循先进先出(FIFO)原则。
Java 集合框架的 Queue
接口提供了队列数据结构的功能。它扩展了 Collection
接口。
实现 Queue 的类
由于 Queue
是一个接口,我们不能直接提供它的实现。
为了使用 Queue
的功能,我们需要使用实现了它的类:
扩展 Queue 的接口
Queue
接口也被各种子接口扩展:
Deque
BlockingQueue
BlockingDeque
队列数据结构的工作原理
在队列中,元素是以先进先出的方式存储和访问的。即,元素从后面添加并从前面移除。
如何使用 Queue?
在 Java 中,我们必须导入 java.util.Queue
包才能使用 Queue
。
// LinkedList 实现的 Queue
Queue<String> animal1 = new LinkedList<>();
// Array 实现的 Queue
Queue<String> animal2 = new ArrayDeque<>();
// 优先队列实现的 Queue
Queue<String> animal3 = new PriorityQueue<>();
这里,我们分别创建了 LinkedList
、ArrayDeque
和 PriorityQueue
类的对象 animal1
、animal2
和 animal3
。这些对象可以使用 Queue
接口的功能。
Queue 的方法
Queue
接口包括了 Collection
接口的所有方法。这是因为 Collection
是 Queue
的超接口。
Queue
接口中一些常用的方法包括:
- add() - 向队列中插入指定的元素。如果任务成功,
add()
返回true
,否则抛出异常。 - offer() - 向队列中插入指定的元素。如果任务成功,
offer()
返回true
,否则返回false
。 - element() - 返回队列的头部。如果队列为空,则抛出异常。
- peek() - 返回队列的头部。如果队列为空,则返回
null
。 - remove() - 返回并移除队列的头部。如果队列为空,则抛出异常。
- poll() - 返回并移除队列的头部。如果队列为空,则返回
null
。
队列接口的实现
1. 实现 LinkedList 类
import java.util.Queue;
import java.util.LinkedList;
class Main {
public static void main(String[] args) {
// 使用 LinkedList 类创建 Queue
Queue<Integer> numbers = new LinkedList<>();
// 向 Queue 提供元素
numbers.offer(1);
numbers.offer(2);
numbers.offer(3);
System.out.println("Queue: " + numbers);
// 访问 Queue 的元素
int accessedNumber = numbers.peek();
System.out.println("访问的元素: " + accessedNumber);
// 从 Queue 中移除元素
int removedNumber = numbers.poll();
System.out.println("