我尝试根据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
这表明该列表显然没有排序。我哪里错了?
答案 0 :(得分:11)
您对sort
的呼唤通过了另一个比较器:
public void sort(){
Collections.sort(list, new PostingsEntryComparator());
}
出于此类目的,PostingsEntryComparator
替换了score
的“自然顺序”,由PostingsEntry
执行Comparable<PostingsEntry>
确定。因此,条目在docID
上进行比较。如果您打印docID
代替score
,您会看到您的列表已根据ID正确排序。
注意:由于整数溢出,减去两个被比较项目的ID可能会产生错误的结果。请改用Integer.compare
,方法与在Double.compare
中正确使用PostingsEntry.compareTo
的方式相同。
答案 1 :(得分:7)
致电时
Collections.sort(list, new PostingsEntryComparator());
您按PostingsEntryComparator
排序,比较docID
s。
如果您想按分数排序,则需要使用Comparable
PostingsEntry
的{{1}}实施方式,您可以通过调用Collections.sort()
而不传递Comparator
来执行此操作:
Collections.sort(list);