上个代码
public static void main(String[] args) {
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
for (int i = 0; i < 100; i++) {
int num = (int)(Math.random()*100);
priorityQueue.add(num);
}
System.out.println(priorityQueue);
}
输出的结果
[0, 2, 2, 3, 3, 12, 2, 4, 6, 5, 7, 30, 33, 13, 10, 16, 10, 22, 23, 23, 19, 16, 13, 33, 33, 47, 49, 29, 19, 30, 57, 43, 39, 61, 47, 79, 40, 37, 23, 37, 34, 64, 33, 39, 56, 23, 18, 69, 52, 39, 93, 70, 53, 80, 74, 64, 43, 56, 24, 78, 73, 90, 63, 87, 50, 41, 98, 95, 71, 81, 80, 87, 80, 48, 59, 47, 84, 79, 23, 94, 48, 48, 56, 80, 83, 91, 96, 80, 55, 74, 59, 59, 34, 84, 22, 88, 77, 81, 76, 79]
我们发现这个序列是无序的,我下意识以为是priorityQueue无序了,其实并不是,只是方法用错了而已,本质上priorityQueue是一个完全二叉树,做一个小顶堆的操作,所以输出的数组是一个二叉树,不能直接使用,假如要获得有序的队列,估计只能一个一个迭代,poll出来。