我正在尝试根据ArrayList对象的PostingsEntry属性对score对象的PostingsEntry进行排序。该列表位于具有PostingsList方法的sort()对象中。

public class PostingsEntry implements Comparable<PostingsEntry>{

    public int docID;
    public double score = 0;
    private TreeSet<Integer> positions = new TreeSet<Integer>();
    /**
     *  PostingsEntries are compared by their score (only relevant
     *  in ranked retrieval).
     *
     *  The comparison is defined so that entries will be put in
     *  descending order.
     */

    public int compareTo( PostingsEntry other ) {
        return Double.compare( other.score, score );
    }
}

public class PostingsList{

    private int position = 0;
    /** The postings list */
    private ArrayList<PostingsEntry> list = new ArrayList<PostingsEntry>();

    private class PostingsEntryComparator implements Comparator<PostingsEntry>{
        @Override
        public int compare(PostingsEntry pA, PostingsEntry pB){
            return pA.docID - pB.docID;
        }
    }
    /** Number of postings in this list. */
    public int size() {
        return list.size();
    }

    /** Returns the ith posting. */
    public PostingsEntry get( int i ) {
    return list.get( i );
    }

    public void sort(){
        Collections.sort(list, new PostingsEntryComparator());
    }

}

我正在尝试对列表进行排序:
// sort postingsList
postingsList.sort();

然后我打印结果:
for(int i=0; i<postingsList.size(); i++){
    System.out.println(index.docNames.get(postingsList.get(i).docID));
    System.out.printf("score: %f\n\n", postingsList.get(i).score);
}

但我得到:
davisWiki/Zombie_Attack_Response_Guide.f
score: 0,019064

davisWiki/EvanGray.f
score: 0,004368

davisWiki/Mortal_Forever.f
score: 0,002708

davisWiki/JasonRifkind.f
score: 0,767518

davisWiki/Measure_Z.f
score: 0,031980

这表明该列表显然没有排序。我要去哪里错了?

最佳答案

您对sort的调用传递了一个不同的比较器:

public void sort(){
    Collections.sort(list, new PostingsEntryComparator());
}

出于这种目的,此PostingsEntryComparatorscore替换了“自然顺序”,这是由PostingsEntryComparable<PostingsEntry>实现实现的。因此,将在条目docID上对条目进行比较。如果您打印docID代替score,则会看到您的列表已根据ID正确排序。

注意:由于整数溢出,正在比较的两个项目的减法ID可能会产生错误的结果。改用 Integer.compare ,就像在Double.compare中正确使用PostingsEntry.compareTo一样。

10-06 09:15