PriorityQueue是Java中基于堆的无界优先队列,默认小顶堆,支持自然排序或自定义Comparator排序,常用于任务调度等场景。

在Java中,PriorityQueue 是一个基于堆结构的无界队列,能够按照元素的优先级自动排序。它常用于需要按优先级处理任务的场景,比如任务调度、Dijkstra最短路径算法等。默认情况下,PriorityQueue使用元素的自然顺序(即实现 Comparable 接口),也可以通过传入 Comparator 自定义排序规则。
PriorityQueue 不是线程安全的,如果在多线程环境下使用,应考虑使用 PriorityBlockingQueue。另外,它不允许插入 null 元素,否则会抛出 NullPointerException。队列头部始终是优先级最高的元素(最小值,默认小顶堆)。插入和删除操作的时间复杂度为 O(log n),获取头部元素为 O(1)。
当存储的元素实现了 Comparable 接口时,如 Integer、String 等,可以直接使用 PriorityQueue:
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.offer(5);
pq.offer(2);
pq.offer(8);
System.out.println(pq.poll()); // 输出 2
PriorityQueue<String> stringPQ = new PriorityQueue<>();
stringPQ.offer("apple");
stringPQ.offer("banana");
stringPQ.offer("cherry");
System.out.println(pq.poll()); // 输出 "apple"
若想让优先队列实现最大值优先(大顶堆),可以传入自定义的 Comparator:
立即学习“Java免费学习笔记(深入)”;
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
maxHeap.offer(3);
maxHeap.offer(1);
maxHeap.offer(4);
System.out.println(maxHeap.poll()); // 输出 4
class Person {
String name;
int age;
Person(String name, int age) { this.name = name; this.age = age; }
}
PriorityQueue<Person> people = new PriorityQueue<>((p1, p2) -> p1.age - p2.age);
people.offer(new Person("Alice", 30));
people.offer(new Person("Bob", 25));
System.out.println(people.poll().name); // 输出 Bob
PriorityQueue 提供了标准的队列操作方法:
基本上就这些。掌握 PriorityQueue 的自然排序与自定义排序方式,能有效应对大多数需要优先处理的业务逻辑。注意不要忽略其非线程安全和不能存 null 的限制。
以上就是在Java中如何使用PriorityQueue实现优先队列_PriorityQueue类应用指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号