简体   繁体   English

Java PriorityQueue和Comparator排序不正确

[英]Java PriorityQueue and Comparator Not Ordering correctly

I am new to Java and am trying to implement a priority queue with a custom comparator. 我是Java新手,正在尝试使用自定义比较器实现优先级队列。 I want to put the Sentences in the queue and have them removed in order to highest score. 我想将句子排在队列中,并删除它们以取得最高分。

For the comparator class I have: 对于比较器类,我有:

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

}

I then print out the sentences like so: 然后,我像这样打印出句子:

PriorityQueue<Sentence> allSentences = new PriorityQueue<Sentence>(new SentenceScoreComparator());
//add sentences

for(Sentence s :allSentences){
            System.out.println(s.getScore()); 
        }

but they are not in order 但他们没有秩序

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

I checked that the queue is using the comparator with the correct comparator method. 我检查队列是否使用具有正确比较器方法的比较器。 Can someone explain what I am missing? 有人可以解释我所缺少的吗?

PriorityQueue never promised to traverse them in order. PriorityQueue从未答应按顺序遍历它们。 From the javadocs : javadocs

This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. 此类及其迭代器实现Collection和Iterator接口的所有可选方法。 The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. 不保证方法iterator()中提供的Iterator以任何特定顺序遍历优先级队列的元素。 If you need ordered traversal, consider using Arrays.sort(pq.toArray()). 如果需要有序遍历,请考虑使用Arrays.sort(pq.toArray())。

You have a typo in the comparator in the second if where o2 score is compared to itself. ifo2分数o2自身进行比较,则第二个比较器中有一个错字。

Replace it with: 替换为:

@Override
public int compare(Sentence o1, Sentence o2) {
    return Double.compare(o1.getScore(), o2.getScore());
}

On top of that, as bradimus answered, PriorityQueue does not guarantee any sorted traversal. 最重要的是,正如bradimus回答的那样, PriorityQueue不保证任何排序遍历。 Use a regular list and sort it for that. 使用常规列表并对其进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM