为优先队列提供更多元素?

Offering more elements to a Priority Queue?

我想知道为什么下面的输出是 [12, 15, 12]?我知道优先队列通过堆对其元素进行排序,但为什么 12 没有放在 15 之前?太感谢了! :)

Queue<Integer> q;
q= new PriorityQueue<>();
q.offer(15);
q.offer(12);
q.offer(2);
q.poll();
q.offer(q.peek());
q.peek();
System.out.println(q);

您应该养成查阅 JDK 类.

的 Javadoc 的习惯

System.out.println(q),根据 its documentation, calls String.valueOf(q), which according to its documentation calls q.toString(), which according to its documentation uses the order of elements from q.iterator(), which according to its documentation 没有任何特定顺序。

如果您考虑优先级队列的实现方式(通常是某种堆结构),这是有道理的:堆不跟踪元素的顺序,除了确保每个节点都有一个比它的所有后代节点都小的值。要 return 元素按有意义的顺序排列,最坏情况下需要 O(n log n) 时间。