Queue是接口,LinkedList实现了Queue接口;队列遵循:先进先出 FIFO,先放进去的元素先拿出来。
import java.util.Queue;
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
// Queue是接口,不能new Queue,用LinkedList做实现类
Queue<Integer> queue = new LinkedList<>();
// 入队:把元素加到队列尾部
queue.offer(10);
queue.offer(20);
queue.offer(30);
// 此时队列:【10,20,30】 10队头,30队尾
// peek():获取队头元素,⭐不删除元素
System.out.println(queue.peek()); //输出10
// poll():取出队头元素,⭐会把队头从队列删掉
System.out.println(queue.poll()); //输出10
//执行完poll之后队列变成:【20,30】
//再peek取队头
System.out.println(queue.peek()); //输出20
// size() 获取队列里面元素个数
System.out.println(queue.size()); //输出2
// isEmpty() 判断队列是否为空,空返回true,不为空false
System.out.println(queue.isEmpty()); //输出false
}
}
核心方法对照表(Queue 常用)
表格
| 方法 | 作用 | 特点 |
|---|---|---|
offer(e) | 入队,加到队列末尾 | 推荐,返回 boolean,添加失败不会抛异常 |
peek() | 读取队头,不移除 | 队列为空返回null |
poll() | 取出队头,移除 | 队列为空返回null |
size() | 获取队列元素数量 | |
isEmpty() | 判断队列是否为空 |
❗不要用
add() remove()(也可以用,但队列空的时候remove()会直接抛异常;poll/peek返回 null 更安全,业务代码优先用 poll、peek、offer)
完整循环把队列全部取完示例
while(!queue.isEmpty()){
Integer item = queue.poll();
System.out.println(item);
}
//输出 20 30,队列清空
底层小知识点
Queue<Integer> queue = new LinkedList<>()
LinkedList双向链表,做队列性能很好:头尾增删快。- 队列规则:先进先出,不能随机取中间元素,只能操作队头、队尾。
拓展:什么场景用队列
- 任务排队、消息排队
- BFS 广度优先遍历(树、图算法)
- 请求排队处理
对比栈
Stack:栈是后进先出;队列先进先出。
坑点提醒
Queue<Integer> q = new LinkedList<>();
q.peek(); //空队列 → 返回null
q.poll(); //空队列 → 返回null
如果直接写int num = q.poll();会自动拆箱,null 拆箱 int 直接空指针,要用包装类Integer接收。
//错误
int val = queue.poll();
//正确
Integer val = queue.poll();
if(val != null){
}

917

被折叠的 条评论
为什么被折叠?



