PriorityQueue增加元素时,并不能使整个数列是有序的,只能保证队首元素是最大值或最小值,其它是乱序的。删除队首元素时,会更新新队首元素。
测试代码如下
@Test
public void test4() {
PriorityQueue<Integer> que = new PriorityQueue<>((a1, a2) -> {
return a2 - a1;
});
que.offer(3);
que.offer(1);
que.offer(2);
System.out.println(que);
System.out.println("peek, " + que.peek() + ", " + que);
System.out.println("poll, " + que.poll() + ", " + que); //删除队首
}
输出结果为
[3, 1, 2] //不是预期的[3, 2, 1]
peek, 3, [3, 1, 2]
poll, 3, [2, 1] //输出队首时,会重新调整