【发布时间】:2014-01-04 03:15:21
【问题描述】:
我正在研究霍夫曼。但是我发现 PriorityQueue 的排序算法有问题;它没有足够的比较!然后我只是写了一个简单的类来测试Collections的排序和PriorityQueue的排序:
public class Student implements Comparable<Student>{
String name;
int score;
int math;
public Student(int score, int math, String name) {
this.name = name;
this.score = score;
this.math = math;
}
public int compareTo(Student other) {
if (this.score > other.score) {
return -1;
} else if (this.score < other.score) {
return 1;
} else {
if (this.math > other.math) {
return -1;
} else {
return 1;
}
}
return 0;
}
public String toString() {
return("[" + name + " has Score: " + score + "(Math: " + math + ")]");
}
}
但我得到了这样的结果(在控制台上):
Priority Queue::::::::::
[Jeremy Lin has Score: 2350(Math: 800)]
[Qian has Score: 2150(Math: 800)]
[PoorMath has Score: 2060(Math: 600)]
[Hui has Score: 1800(Math: 690)]
[Kaiyu has Score: 2060(Math: 800)]
[Chao has Score: 0(Math: 0)]
ArrayList sorted::::::::
[Jeremy Lin has Score: 2350(Math: 800)]
[Qian has Score: 2150(Math: 800)]
[Kaiyu has Score: 2060(Math: 800)]
[PoorMath has Score: 2060(Math: 600)]
[Hui has Score: 1800(Math: 690)]
[Chao has Score: 0(Math: 0)]
如何解释?太诡异了!
非常感谢!!
【问题讨论】:
-
你的 compareTo() 方法永远不会返回零。
-
你可以使用
Integer.compare(int x, int y) -
提供您的测试方法。我的猜测是您正在迭代 PriorityQueue,它不保证以任何特定顺序进行迭代:此类及其迭代器实现了 Collection 和 Iterator 接口的所有可选方法。方法 iterator() 中提供的 Iterator 不能保证以任何特定顺序遍历优先级队列的元素。如果您需要有序遍历,请考虑使用 Arrays.sort(pq.toArray())。 (来自docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html)
-
我试过了,我通过使用
poll方法得到了按顺序显示的结果,该方法从队列中删除了“最小”元素并返回它。
标签: java algorithm sorting arraylist priority-queue