温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java Queue队列如何出队

发布时间:2026-10-04 16:10:03 来源:亿速云 阅读:91 作者:小樊 栏目:编程语言

在 Java 中,Queue(队列) 的出队(从队列中取出/移除元素)通常有以下几种方式,取决于你是否希望在队列为空时抛出异常还是返回特殊值。


一、常用出队方法对比

方法 行为 队列为空时
remove() 出队并删除队首元素 抛出 NoSuchElementException
poll() 出队并删除队首元素 返回 null
element() 查看队首(不出队) 抛出 NoSuchElementException
peek() 查看队首(不出队) 返回 null

✅ 实际开发中最常用的是 poll()


二、示例代码

1️⃣ 使用 poll()(推荐)

import java.util.LinkedList;
import java.util.Queue;

public class QueueDemo {
    public static void main(String[] args) {
        Queue<String> queue = new LinkedList<>();
        queue.offer("A");
        queue.offer("B");
        queue.offer("C");

        // 出队
        String item = queue.poll();
        System.out.println(item); // A
        System.out.println(queue); // [B, C]
    }
}

2️⃣ 使用 remove()

String item = queue.remove(); // 队列为空会抛异常

3️⃣ 只查看队首,不出队

String head = queue.peek();

三、常见实现类

Queue<Integer> q1 = new LinkedList<>();
Queue<Integer> q2 = new ArrayDeque<>();
Queue<Integer> q3 = new PriorityQueue<>();
  • LinkedList:最常用
  • ArrayDeque:性能更好(推荐)
  • PriorityQueue:优先级队列(不是 FIFO)

四、循环出队示例

while (!queue.isEmpty()) {
    System.out.println(queue.poll());
}

如果你用的是 阻塞队列(BlockingQueue),出队方式会不同(如 take()),需要的话我可以单独讲。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手