问题
i am very confused with this little example of java.util.PriorityQueue and my own Comparator:
In this code i get a wrong order in the queue.
The result is: 5,8,7instead of 5,7,8
Is there anything wrong with my Comparator<Vertex> ? Thank you for your help.
public class Test {
public static void main(String[] args) {
PriorityQueue<Vertex> priorityQueue = new PriorityQueue<Vertex>(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Vertex u = (Vertex) o1;
Vertex v = (Vertex) o2;
return Integer.compare(new Integer(u.distance), new Integer(v.distance));
}
});
Vertex vertex1 = new Vertex(1);
Vertex vertex2 = new Vertex(2);
Vertex vertex3 = new Vertex(3);
Vertex vertex4 = new Vertex(4);
vertex1.distance = 8;
vertex2.distance = 5;
vertex3.distance = 7;
priorityQueue.add(vertex1);
priorityQueue.add(vertex2);
priorityQueue.add(vertex3);
}
private static class Vertex {
int distance;
int id;
public Vertex(int id) {
this.id = id;
}
}
}
回答1:
A PriorityQueue doesn't store its elements in order. It gives them back to you in order.
If you called poll() three times on the PriorityQueue, you'd get your elements back in the appropriate order.
来源:https://stackoverflow.com/questions/26784670/wrong-order-in-java-util-priorityqueue-and-specific-comparator