如何按排序顺序将优先级转换为列表?

发布于 2025-02-09 17:52:16 字数 278 浏览 3 评论 0原文

如何将PriortityQueue转换为list在不更改(poll()等)的情况下 priortityqueue ?我们要同时保留PriorityQueuelist

将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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白馒头 2025-02-16 17:52:16

PriorityQueue中的Javadoc中所述:

方法迭代器中提供的迭代器不能保证以任何特定顺序遍历优先级队列的元素。

必须这样做似乎是一个奇怪的情况。您可能需要查看用例,并确保使用最佳解决方案。例如,您可以使用treeset而不是list。或者,您可能首先需要重新考虑您要使用队列的工作。

但是要回答您的问题,一种非常简单的(但可能不高效?)将PriortityQueue的优先元素复制到list> list的方法是:

PriorityQueue<T> pq = ...
List<T> myList = new ArrayList<>(pq);
Collections.sort(myList, pq.comparator());

As noted in the JavaDoc for PriorityQueue:

The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order.

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 a List, 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 a List would be:

PriorityQueue<T> pq = ...
List<T> myList = new ArrayList<>(pq);
Collections.sort(myList, pq.comparator());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文