2 回答
TA贡献1804条经验 获得超3个赞
根据文档,aPriorityQueue是:
基于优先级堆的无界优先级队列。
通过查看源代码,我们可以在 backing 声明上方看到以下内容Object[]:
/**
* Priority queue represented as a balanced binary heap: the two
* children of queue[n] are queue[2*n+1] and queue[2*(n+1)]. The
* priority queue is ordered by comparator, or by the elements'
* natural ordering, if comparator is null: For each node n in the
* heap and each descendant d of n, n <= d. The element with the
* lowest value is in queue[0], assuming the queue is nonempty.
*/
因此,迭代顺序不会是您所期望的。
该文件还指出:
方法 iterator() 中提供的 Iterator 和方法 spliterator() 中提供的 Spliterator 不能保证以任何特定顺序遍历优先级队列的元素。如果您需要有序遍历,请考虑使用 Arrays.sort(pq.toArray())。
TA贡献1776条经验 获得超12个赞
还想补充一点,如果您希望队列结果按顺序排列,您可以轮询整个队列并将其清空。
while (q2.size() > 0) {
System.out.println(q2.poll());
}
将打印出您期望的内容。
添加回答
举报