java.util.PriorityQueue和特定Comparator中的顺序错误 [英] Wrong order in java.util.PriorityQueue and specific Comparator

查看:220
本文介绍了java.util.PriorityQueue和特定Comparator中的顺序错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对java.util.PriorityQueue和我自己的比较器的这个小例子非常困惑:

i am very confused with this little example of java.util.PriorityQueue and my own Comparator:

在这段代码中,我在队列中得到错误的顺序。
结果是: 5,8,7 而不是 5,7,8
我的比较器< Vertex> 有什么问题吗?感谢您的帮助。

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


推荐答案

PriorityQueue 不按顺序存储其元素。它按顺序给你回复。

A PriorityQueue doesn't store its elements in order. It gives them back to you in order.

如果您在 PriorityQueue poll()三次c>,你会按照适当的顺序恢复你的元素。

If you called poll() three times on the PriorityQueue, you'd get your elements back in the appropriate order.

这篇关于java.util.PriorityQueue和特定Comparator中的顺序错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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