Wrong order in java.util.PriorityQueue and specific Comparator

爱⌒轻易说出口 提交于 2019-12-20 07:47:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!