-1
错了,我很迷茫与java.util.PriorityQueue中的这个小例子,我自己比较:秩序java.util.PriorityQueue中和具体比较
在这段代码中,我得到队列中的错误的顺序。 结果是:5,8,7
而不是5,7,8
我的Comparator<Vertex>
有什么问题吗?感谢您的帮助。
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;
}
}
}
为什么使用'new Integer(...)'?不鼓励使用'Integer'的构造函数,而不使用'Integer.valueOf'的构造函数,但即使调用'Integer.valueOf'也是不必要的,因为Java的自动装箱会在需要时为您执行。但在这里它并不是必需的,因为'Integer.compare'需要'int'值作为参数。因此,您正在创建过时的Integer对象,并让Java的auto(un)boxing将它们转换回int值... – Holger 2014-11-06 16:53:12