Java:PriorityQueue从自定义比较器返回错误的排序? [英] Java: PriorityQueue returning incorrect ordering from custom comparator?

查看:349
本文介绍了Java:PriorityQueue从自定义比较器返回错误的排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个自定义比较器来比较我的节点类,但是java优先级队列未按正确的顺序返回我的项目。

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.

这是我的比较器:

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返回double的位置。但是,在将几个节点插入优先级队列之后,我使用以下命令将它们打印出来:

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());
}

其结果是:

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.

迈克

推荐答案

如何打印这些值?我不认为 PriorityQueue 的迭代器可以提供与整个类相同的排序保证,所以如果您正在这样做,则很有可能

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 doing

for(Node n : queue) {
System.out.println(n.getF());
}

您将获得无序的输出。订购保证仅适用于优惠收取投票 peek 以及其他一些方法。

You'll be getting unordered output. The ordering assurance only applies to offer, take, poll, peek, and possibly some other methods.

在javadocs中的迭代器中特别提到了优先级队列 http://java.sun.com/javase/6 /docs/api/java/util/PriorityQueue.html

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

这篇关于Java:PriorityQueue从自定义比较器返回错误的排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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