PriorityQueue返回元素的顺序错误 [英] PriorityQueue returning elements in wrong order
问题描述
我有一个类Person
,它具有两个属性Name(String
)和Weight(Integer
).
I have a class Person
which has two attributes Name(String
) and Weight(Integer
).
我想根据元素的权重降序存储在PriorityQueue中,即元素在队列顶部的权重越高.
I want to store elements in PriorityQueue according to their weight in descending order, i.e. higher the weight the top the element is in the queue.
到目前为止,我已经尝试过:
I have tried this so far:
PriorityQueue<Person> personPriorityQueue = new PriorityQueue<Person>((a,b)-> Integer.compare(a.getWeight(), b.getWeight()));
personPriorityQueue.add(new Person(40,"N1"));
personPriorityQueue.add(new Person(60,"N2"));
personPriorityQueue.add(new Person(50,"N3"));
personPriorityQueue.forEach(s-> System.out.println(s.getName()));
我得到的输出是:
N1
N2
N3
我应该得到:
N2
N3
N1
推荐答案
如果您查看PriorityQueue.iterator
方法的文档注释,则会显示:
If you look at the documentation comment for the PriorityQueue.iterator
method it says:
返回此队列中元素的迭代器.迭代器确实 不会以任何特定顺序返回元素.
Returns an iterator over the elements in this queue. The iterator does not return the elements in any particular order.
forEach
语句在下面使用迭代器,从而扭曲了从PriorityQueue
检索的元素的顺序.您必须在队列上使用poll
方法来解决此问题. poll
方法从队列的开头删除该元素.除此之外,您还必须修复比较器以颠倒顺序,因为您需要按降序对元素进行排序.这是代码.
The forEach
statement uses an iterator underneath, distorting the order of the elements retrieved from the PriorityQueue
. You have to use the poll
method on the queue to solve the issue. The poll
method removes the element from the head of the queue. Apart from that you have to fix the comparator to reverse the order since you need elements to be sorted in descending order. Here's the code.
Queue<Person> personPriorityQueue = new PriorityQueue<>(
Comparator.comparingInt(Person::getWeight).reversed());
while(!personPriorityQueue.isEmpty())
System.out.println(personPriorityQueue.poll().getName());
这篇关于PriorityQueue返回元素的顺序错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!