【Queue 队列 + LinkedList 实现 完整讲解】

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,队列清空

底层小知识点

  1. Queue<Integer> queue = new LinkedList<>()
    LinkedList双向链表,做队列性能很好:头尾增删快。
  2. 队列规则:先进先出,不能随机取中间元素,只能操作队头、队尾。

拓展:什么场景用队列

  1. 任务排队、消息排队
  2. BFS 广度优先遍历(树、图算法)
  3. 请求排队处理

对比栈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){
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值