Java中PriorityQueue是基于优先堆的无界队列,默认按自然升序排列,最小元素先出队,不支持null元素,入队和出队时间复杂度均为O(log n)。

Java中的PriorityQueue是一个基于优先堆的无界队列,它允许我们按照元素的优先级进行出队操作。默认情况下,PriorityQueue是按自然顺序(升序)排序的,也就是说最小的元素最先出队。它不支持null元素,并且入队和出队的时间复杂度为O(log n)。
PriorityQueue实现了Queue接口,可以像普通队列一样使用offer()、poll()、peek()等方法。
示例代码:
PriorityQueue<Integer> pq = new PriorityQueue<>(); pq.offer(5); pq.offer(1); pq.offer(3); <p>System.out.println(pq.peek()); // 输出 1 System.out.println(pq.poll()); // 输出 1 System.out.println(pq.poll()); // 输出 3</p>
如果想改变默认排序方式,比如让大的元素优先级更高,可以通过传入Comparator来实现。
立即学习“Java免费学习笔记(深入)”;
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a); pq.offer(5); pq.offer(1); pq.offer(3); System.out.println(pq.poll()); // 输出 5
对于自定义对象,比如Person类按年龄排序:
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
<p>PriorityQueue<Person> pq = new PriorityQueue<>((p1, p2) -> p1.age - p2.age);
pq.offer(new Person("Alice", 30));
pq.offer(new Person("Bob", 20));
System.out.println(pq.poll().name); // 输出 Bob</p>PriorityQueue常用于需要动态维护最值的问题,比如Top K、合并K个有序链表、哈夫曼编码等。
基本上就这些。掌握构造、添加、取出和自定义排序就能应对大多数情况了。用起来不复杂,但容易忽略比较器的细节,特别是负数处理时建议用Integer.compare避免溢出。
以上就是Java中PriorityQueue优先队列使用方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号