PriorityQueue通过二叉小顶堆实现。
这个优先队列中的元素可以默认自然排序或者通过提供的Comparator(比较器)在队列实例化的时排序。
PriorityQueue是非线程安全的,所以Java提供了PriorityBlockingQueue(实现BlockingQueue接口)用于Java多线程环境。
PriorityQueue <Integer> maxHeap = new PriorityQueue<Integer>(k);
maxHeap.add(3);
maxHeap.add(1);
maxHeap.add(4);
maxHeap.add(3);
for(int i:maxHeap)
{
System.out.print(i+" ");
}
System.out.println();
maxHeap.remove();
maxHeap.remove();
for(int i:maxHeap)
{
System.out.print(i+" ");
}
System.out.println();
这段代码的输出如下所示:
1 3 4 3
3 4
从上述结果可以看出,PriorityQueue默认采用最小堆来实现。
通过重写compare方法,将PriorityQueue改为最大堆来实现。
PriorityQueue <Integer> maxHeap = new PriorityQueue<Integer>(k,new Comparator<Integer>() {
@Override
public int compare(Integer o1,Integer o2)
{
return o2.compareTo(o1);
}
});
maxHeap.add(3);
maxHeap.add(1);
maxHeap.add(4);
maxHeap.add(3);
for(int i:maxHeap)
{
System.out.print(i+" ");
}
System.out.println();
maxHeap.remove();
maxHeap.remove();
for(int i:maxHeap)
{
System.out.print(i+" ");
}
System.out.println();
输出为:
4 3 3 1
3 1