原文:http://blog.csdn.net/a15994269853/article/details/20571317
优先级队列是不同于先进先出队列的另一种队列。每次从队列中取出的是具有最高优先权的元素。PriorityQueue是从JDK1.5开始提供的新的数据结构接口。如果不提供Comparator的话,优先队列中元素默认按自然顺序排列,也就是数字默认是小的在队列头,字符串则按字典序排列。
在这里我先罗列一组程序对比一下:
- import java.util.*;
- public class TestPriorityQueue{
- public static void main(String[] args){
- PriorityQueue<Integer> pq = new PriorityQueue<Integer>(5,new Comparator<Integer>(){
- @Override
- public int compare(Integer o1, Integer o2) {
- if(o2 > o1){
- return 1;
- }
- else if(o2 < o1){
- return -1;
- }
- else {
- return 0;
- }
- }
- });
- pq.offer(6);
- pq.offer(-3);
- pq.offer(9);
- pq.offer(0);
- pq.offer(9);
- System.out.println(pq);
- while(!pq.isEmpty()) {
- System.out.print(pq.poll()+",");
- }
- }
- }
结果如下:
- [9, 9, 6, -3, 0]
- 9,9,6,0,-3,
分析为什么pq输出是 [9, 9, 6, -3, 0],原因是pq是按照对象添加到堆中的顺序来的。为什么会这样,我现在画一个示意图:
这里为什么按照大堆的顺序来的,这是否按照什么来排序,需要看我们重载的compare函数。
其实默认情况下是按照最小堆来排序的,下面 介绍一种不重载compare函数的情况:
- import java.util.*;
- public class TestPriorityQueue{
- public static void main(String[] args){
- PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
- pq.offer(6);
- pq.offer(-3);
- pq.offer(9);
- pq.offer(0);
- pq.offer(9);
- System.out.println(pq);
- while(!pq.isEmpty()) {
- System.out.print(pq.poll()+",");
- }
- }
- }
- [-3, 0, 9, 6, 9]
- -3,0,6,9,9,