0%

Java集合-PriorityQueue

简单整理一下Java集合中PriorityQueue(优先队列)的使用。
参考博客:Java的优先队列PriorityQueue详解PriorityQueue的用法和底层实现原理

一. 基本介绍

Java中的PriorityQueue可以简单看做Java对数据结构——“堆”的实现,是基于优先堆的一个无界队列(即无固定长度,可以指定初始大小,后续可自动扩容)。

不允许空值,不支持non-comparable(不可比较)对象。对象的比较基于实现Comparable接口后的自然排序,或者提供Comparator(比较器)自定义排序。PriorityQueue默认实现最小堆。当有多个对象具有相同的排序时,会随机返回。

PriorityQueue是非线程安全的,Java提供了PriorityBlockingQueue用于多线程环境。

二. 常用方法

1
2
3
4
5
peek(); // 返回堆顶的元素
poll(); // 返回堆顶的元素,并移除该元素
add(); // 添加元素
size(); // 返回堆内元素的个数
isEmpty() // 判断是否为空

三. 具体使用

3.1 队列保存的是基本数据类型的包装类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//自定义比较器,降序排列
static Comparator<Integer> cmp = new Comparator<Integer>() {
public int compare(Integer e1, Integer e2) {
return e2 - e1;
}
};
public static void main(String[] args) {
//不用比较器,默认升序排列
Queue<Integer> q = new PriorityQueue<>();
q.add(3);
q.add(2);
q.add(4);
while(!q.isEmpty())
{
System.out.print(q.poll()+" ");
}
/**
* 输出结果
* 2 3 4
*/
//使用自定义比较器,降序排列
Queue<Integer> qq = new PriorityQueue<>(cmp);
qq.add(3);
qq.add(2);
qq.add(4);
while(!qq.isEmpty())
{
System.out.print(qq.poll()+" ");
}
/**
* 输出结果
* 4 3 2
*/
}