[英]Java PriorityQueue and Comparator Not Ordering correctly
我是Java新手,正在尝试使用自定义比较器实现优先级队列。 我想将句子排在队列中,并删除它们以取得最高分。
对于比较器类,我有:
public class SentenceScoreComparator implements Comparator<Sentence> {
@Override
public int compare(Sentence o1, Sentence o2) {
if (o2.getScore() > o1.getScore()) return -1;
//fixed typo
if (o2.getScore() < o1.getScore()) return 1;
return 0;
}
}
然后,我像这样打印出句子:
PriorityQueue<Sentence> allSentences = new PriorityQueue<Sentence>(new SentenceScoreComparator());
//add sentences
for(Sentence s :allSentences){
System.out.println(s.getScore());
}
但他们没有秩序
0.34432960587450223
0.47885099912108975
0.10991840331015199
0.36222267254836954
0.05164923572003221
0.5366117828694823
0.3891453014131773
0.0961512261934429
0.5566040852233918
0.5079687049927742
0.7628021620154812
0.6023121606121791
0.25695632228681914
0.15701049878801304
0.1260031244674359
0.36516025683986736
0.3846995962155155
我检查队列是否使用具有正确比较器方法的比较器。 有人可以解释我所缺少的吗?
PriorityQueue
从未答应按顺序遍历它们。 从javadocs :
此类及其迭代器实现Collection和Iterator接口的所有可选方法。 不保证方法iterator()中提供的Iterator以任何特定顺序遍历优先级队列的元素。 如果需要有序遍历,请考虑使用Arrays.sort(pq.toArray())。
if
将o2
分数o2
自身进行比较,则第二个比较器中有一个错字。
替换为:
@Override
public int compare(Sentence o1, Sentence o2) {
return Double.compare(o1.getScore(), o2.getScore());
}
最重要的是,正如bradimus回答的那样, PriorityQueue
不保证任何排序遍历。 使用常规列表并对其进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.