Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparator not working correctly for Priorityqueue Java

I am adding edges to a PriorityQueue but for some reason they do not get sorted by their value, leading to a faulty result later.

My edge class looks like this

class Edge implements Comparable<Edge>{
int value;
String dest;
String start;

public Edge(String start, String dest, int g) {
    this.dest = dest;
    value = g;
    this.start = start;
}
@Override
public int compareTo(Edge o) {
    int temp = value - o.value;
    if (temp > 0) {
        return 1;
    }
    if (temp < 0) {
        return -1;
    }
    return 0;
}

Yet, when I run my code where I do addAll on a LinkedList belonging to the Node "Springfield, MO" to the PriorityQueue, the Edges get sorted in the wrong order as seen below, what is the issue?

queue.addAll(list.get(node));

enter image description here

I have tried to make a specific comparator class for Edge and using it as a parameter in the PriorityQueue but I still get the same result.

like image 749
Slayahh Avatar asked Jul 26 '26 17:07

Slayahh


1 Answers

The internal structure of the PriorityQueue is not ordered, it is a heap, you can check this question.

When you retrieve data using method peek or poll, it is guranteed to be ordered.

But be careful when you iterator the queue:

The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).

like image 158
xingbin Avatar answered Jul 29 '26 06:07

xingbin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!