Java: PriorityQueue returning incorrect ordering from custom comparator??

Posted by Michael Simpson on Stack Overflow See other posts from Stack Overflow or by Michael Simpson
Published on 2010-06-15T19:50:46Z Indexed on 2010/06/15 19:52 UTC
Read the original article Hit count: 178

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about java

Related posts about priority-queue