PriorityQueue返回元素的顺序错误 [英] PriorityQueue returning elements in wrong order

查看:92
本文介绍了PriorityQueue返回元素的顺序错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆