优先队列的用法

### Java 优先队列 `PriorityQueue` 使用教程及示例 Java 中的 `PriorityQueue` 是一个基于堆(heap)实现的优先队列,默认情况下按照自然顺序进行排序。它常用于需要根据优先级处理任务或数据的场景,例如调度算法、图算法中的 Dijkstra 算法等。 #### 1. 创建与初始化 可以通过不同的构造方法创建 `PriorityQueue` 实例: - **默认构造函数**:使用默认容量(初始为 11),并按照自然顺序排序。 ```java PriorityQueue<Integer> queue = new PriorityQueue<>(); ``` - **指定初始容量**: ```java PriorityQueue<Integer> queue = new PriorityQueue<>(10); ``` - **自定义比较器**:通过提供 `Comparator` 来定义自定义排序规则。 ```java PriorityQueue<Integer> queue = new PriorityQueue<>((a, b) -> b - a); // 降序排列 ``` - **从集合中初始化**:可以将已有的 `SortedSet` 或其他集合转换为 `PriorityQueue` [^2]。 ```java SortedSet<Integer> sortedSet = new TreeSet<>(Arrays.asList(5, 3, 4, 1, 2)); PriorityQueue<Integer> queue = new PriorityQueue<>(sortedSet); ``` #### 2. 常用方法 | 方法名 | 描述 | |--------------|--------------------------------| | `add(E e)` | 将元素插入队列,若队列已满则抛出异常。 | | `offer(E e)` | 将元素插入队列,若队列已满则返回 `false`。 | | `poll()` | 获取并移除队列头部元素(优先级最高的)。 | | `peek()` | 获取但不移除队列头部元素。 | | `size()` | 返回队列中元素的数量。 | | `isEmpty()` | 判断队列是否为空。 | #### 3. 示例代码 以下是一个简单的 `PriorityQueue` 使用示例,展示了如何添加元素并按优先级取出: ```java import java.util.PriorityQueue; public class PriorityQueueExample { public static void main(String[] args) { PriorityQueue<Integer> queue = new PriorityQueue<>(); queue.add(5); queue.add(4); queue.add(3); queue.add(2); queue.add(1); while (!queue.isEmpty()) { System.out.println(queue.poll()); // 输出顺序为 1, 2, 3, 4, 5 } } } ``` 上述代码中,`PriorityQueue` 默认是小顶堆,因此最小的元素始终在队列头部被取出 [^3]。 #### 4. 自定义对象排序 当使用自定义类时,必须实现 `Comparable` 接口或提供 `Comparator`,否则会抛出 `ClassCastException` [^4]。 ```java class Customer implements Comparable<Customer> { private String name; private int priority; public Customer(String name, int priority) { this.name = name; this.priority = priority; } @Override public int compareTo(Customer other) { return Integer.compare(this.priority, other.priority); // 按优先级升序排列 } @Override public String toString() { return name + " (Priority: " + priority + ")"; } } // 使用示例 PriorityQueue<Customer> customerQueue = new PriorityQueue<>(); customerQueue.add(new Customer("Alice", 3)); customerQueue.add(new Customer("Bob", 1)); customerQueue.add(new Customer("Charlie", 2)); while (!customerQueue.isEmpty()) { System.out.println(customerQueue.poll()); } ``` 输出结果将是按照优先级从小到大排序的客户信息。 #### 5. 应用场景 - **任务调度**:操作系统中进程调度可使用优先队列实现。 - **事件驱动系统**:如模拟系统中事件按时间顺序处理。 - **图算法**:Dijkstra 算法中使用优先队列优化查找最短路径的过程。 - **合并多个有序流**:如归并多个排序好的输入流。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值