Java:PriorityQueue 从自定义比较器返回错误的顺序?
我已经编写了一个自定义比较器来比较我的节点类,但是 java 优先级队列没有以正确的顺序返回我的项目。
这是我的比较器:
public int compare(Node n1, Node n2){
if (n1.getF() > n2.getF()){
return +1;
}
else if (n1.getF() < n2.getF()){
return -1;
}
else { // equal
return 0;
}
}
其中 getF 返回双精度值。但是,在将多个节点插入优先级队列后,我使用以下命令将它们打印出来:
while(open.size() > 0) {
Node t = (Node)(open.remove());
System.out.println(t.getF());
}
其结果是:
6.830951894845301
6.830951894845301
6.0
6.0
5.242640687119285
7.4031242374328485
7.4031242374328485
8.071067811865476
有什么想法为什么会这样吗?我的比较器错了吗?谢谢。
麦克风
I've written a custom comparator to compare my node classes, but the java priority queue is not returning my items in the correct order.
Here is my comparator:
public int compare(Node n1, Node n2){
if (n1.getF() > n2.getF()){
return +1;
}
else if (n1.getF() < n2.getF()){
return -1;
}
else { // equal
return 0;
}
}
Where getF returns a double. However after inserting several Nodes into the priority queue, I print them out using:
while(open.size() > 0) {
Node t = (Node)(open.remove());
System.out.println(t.getF());
}
Which results in:
6.830951894845301
6.830951894845301
6.0
6.0
5.242640687119285
7.4031242374328485
7.4031242374328485
8.071067811865476
Any ideas why this is so? Is my comparator wrong? Thanks.
Mike
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你如何打印这些值?我不认为
PriorityQueue
中的迭代器提供与整个类相同的排序保证,因此如果您这样做,您可能会得到无序的输出。顺序保证仅适用于
offer
、take
、poll
、peek
以及可能的其他一些方法。在优先级队列的 javadoc 中特别提到了迭代器 http://java.sun.com/javase/6/docs/api/java/util/PriorityQueue.html
How are you printing out those values? I don't think the iterator from
PriorityQueue
provides the same ordering assurances that the overall class does, so potentially if you're doingYou'll be getting unordered output. The ordering assurance only applies to
offer
,take
,poll
,peek
, and possibly some other methods.There's a special mention on the iterator in the javadocs for priority queue http://java.sun.com/javase/6/docs/api/java/util/PriorityQueue.html
不知道您的代码有什么问题,但这对我有用:
输出:
确保
getF()
不会意外返回 double 的 int 版本。更新:插入后无法更新定义元素顺序的数据。在这种情况下,您需要提取元素,更新它,然后重新插入它。
Don't know what's wrong with your code, but this works for me:
Output:
Make sure
getF()
doesn't accidentally return an int-version of the double.Update: You cannot update the data which defines the order of the elements after insertion. In that case you need to extract the element, updated it, and reinsert it.