簡體   English   中英

Java PriorityQueue和Comparator排序不正確

[英]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())。

ifo2分數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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM