244. Java 集合 - 使用 Queue 接口建模 FIFO 队列
在 Java 中,Queue 接口专门用来建模 FIFO(First-In, First-Out,先进先出)队列。
但在实际使用队列时,我们经常会遇到两个边界情况:
- 队列已满(比如,容量有限的阻塞队列)
- 队列为空(没有元素可以取出)
针对这些情况,Queue 接口提供了两种处理策略:
- 抛出异常
- 返回特殊值(如
false或null)
📋 Queue 中的方法及其行为总结表
| 操作 | 方法 | 队列已满或为空时的行为 |
|---|---|---|
| 插入元素 | add(element) | 如果队列已满,抛出 IllegalStateException |
| 插入元素 | offer(element) | 如果队列已满,返回 false |
| 移除元素 | remove() | 如果队列为空,抛出 NoSuchElementException |
| 移除元素 | poll() | 如果队列为空,返回 null |
| 查看元素 | element() | 如果队列为空,抛出 NoSuchElementException |
| 查看元素 | peek() | 如果队列为空,返回 null |
🛠️ 示例演示:异常 vs 特殊值
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
// 插入元素
queue.offer("A");
queue.offer("B");
System.out.println("Queue: " + queue); // [A, B]
// 查看队头元素,不移除
System.out.println("Peek: " + queue.peek()); // A
// 移除元素
System.out.println("Poll: " + queue.poll()); // A
System.out.println("Queue after poll: " + queue); // [B]
// 移除剩下的元素
queue.poll(); // 移除 B
// 此时队列为空
System.out.println("Queue now: " + queue); // []
// 安全操作:peek() 返回 null
System.out.println("Peek empty queue: " + queue.peek()); // null
// 安全操作:poll() 返回 null
System.out.println("Poll empty queue: " + queue.poll()); // null
// 不安全操作:remove() 抛出异常
try {
queue.remove();
} catch (Exception e) {
System.out.println("Exception on remove(): " + e);
}
// 不安全操作:element() 抛出异常
try {
queue.element();
} catch (Exception e) {
System.out.println("Exception on element(): " + e);
}
}
}
输出结果:
Queue: [A, B]
Peek: A
Poll: A
Queue after poll: [B]
Queue now: []
Peek empty queue: null
Poll empty queue: null
Exception on remove(): java.util.NoSuchElementException
Exception on element(): java.util.NoSuchElementException
🔥 小结
- 如果你想在队列已满或为空时,避免抛异常,请使用:
offer(element)插入元素poll()移除元素peek()查看元素
- 如果你希望在队列已满或为空时,通过异常捕获异常情况,请使用:
add(element)插入元素remove()移除元素element()查看元素
✅ 安全操作(推荐在不确定队列状态时使用):offer()、poll()、peek()
🚨 不安全操作(需要确保队列非满/非空):add()、remove()、element()
🧐 互动问题
问题:
在一个空队列上调用 poll() 方法,会返回什么?抛出异常吗?
答案:
不会抛出异常,而是返回 null!