Java Queue 常见的方法

  1. add(E), offer(E) 在尾部添加:
    1. 实现类禁止添加 null 元素,否则会报空指针 NullPointerException;
    2. 不同之处在于 add() 方法在添加失败(比如队列已满)时会报 一些运行时错误 错;而 offer() 方法即使在添加失败时也不会奔溃,只会返回 false。
  2. remove(), poll() 删除并返回头部:
    1. 当队列为空时 remove() 方法会报 NoSuchElementException 错; 而 poll() 不会奔溃,只会返回 null。
  3. element(), peek() 获取但不删除:
    1. 当队列为空时 element() 抛出异常;peek() 不会奔溃,只会返回 null。

欢迎关注我的公众号Godyvvva,回复Java资料免费获取Java学习资料,需要自取,过时不候。
### Java队列的操作与实现 #### 队列简介 队列是一种遵循先进先出(FIFO)原则的数据结构。Java 提供了多种类型的 `Queue` 接口及其具体实现类来满足不同的需求。 #### 常见Queue 实现类 常见的 `Queue` 实现类包括但不限于: - **LinkedList**: 双向链表实现,支持高效的插入和删除操作。 - **PriorityQueue**: 支持优先级排序的无界队列。 - **ArrayBlockingQueue**: 由数组支持的有界阻塞队列。 - **LinkedBlockingQueue**: 由链表构成的可选容量有界的阻塞队列。 #### 使用示例 下面是一个简单的例子展示如何创建并使用不同类型的队列: ```java import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; public class QueueExample { public static void main(String[] args) { // 创建 LinkedList 类型的队列 Queue<String> linkedListQueue = new LinkedList<>(); // 添元素到队列中 linkedListQueue.offer("First"); linkedListQueue.offer("Second"); linkedListQueue.offer("Third"); System.out.println("Elements in LinkedList Queue: " + linkedListQueue); // 移除头部元素 String removedElement = linkedListQueue.poll(); System.out.println("Removed element from LinkedList Queue: " + removedElement); System.out.println("After removal, elements in LinkedList Queue: " + linkedListQueue); // 获取但不移除头部元素 String peekedElement = linkedListQueue.peek(); System.out.println("Peeked at head of LinkedList Queue without removing it: " + peekedElement); // 创建 PriorityQueue 并添元素 Queue<Integer> priorityQueue = new PriorityQueue<>(); priorityQueue.offer(10); priorityQueue.offer(5); priorityQueue.offer(7); System.out.println("\nElements in Priority Queue: " + priorityQueue); // 移除最小值 Integer minElement = priorityQueue.poll(); System.out.println("Removed minimum value from Priority Queue: " + minElement); System.out.println("After removal, elements in Priority Queue: " + priorityQueue); } } ``` 此代码展示了两种不同类型队列的基本用法:基于链接列表的常规 FIFO 行为以及具有自然顺序排列特性的优先级队列[^2]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值