如何按排序顺序将优先级转换为列表?
如何将PriortityQueue
转换为list
在不更改(poll()等)的情况下
priortityqueue ?我们要同时保留PriorityQueue
和list
。
将2、3、1添加到PriorityQueue
将其排序为1、2、3。 2,3,1。 1。我想这与PriorityQueue
的实现有关。
How do you convert a PriorityQueue
to a List
in the sorted order without altering (poll(), etc
) the PriorityQueue
? We want to keep both the PriorityQueue
and the List
.
Adding 2, 3, 1 to a PriorityQueue
will sort it to 1, 2, 3. Creating an ArrayList
from the PriorityQueue
will have an order of 2, 3, 1. The iterator()
and toArray()
methods from the PriorityQueue
will also have an order of 2, 3, 1. I guess it has to do with the implementation of PriorityQueue
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如
PriorityQueue
中的Javadoc中所述:必须这样做似乎是一个奇怪的情况。您可能需要查看用例,并确保使用最佳解决方案。例如,您可以使用
treeset
而不是list
。或者,您可能首先需要重新考虑您要使用队列的工作。但是要回答您的问题,一种非常简单的(但可能不高效?)将
PriortityQueue
的优先元素复制到list> list
的方法是:As noted in the JavaDoc for
PriorityQueue
:It seems like an odd scenario to have to do this. You may want to review your use case and ensure you're using the best solution. You could use a
TreeSet
instead instead of aList
, for example. Or you might need to rethink what you're trying to do with your queue in the first place.But to answer your question, a pretty straightforward (but maybe not efficient?) way to copy a
PriorityQueue
's prioritized elements into aList
would be: