Collections.sort () leaves my list unsorted

I am trying to sort ArrayList objects from PostingsEntry according to the score attribute of PostingsEntry objects. The list is in the PostingsList object, which has a sort() method.

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

I am trying to sort the list here:

 // sort postingsList postingsList.sort(); 

And I print the results:

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

But I get:

 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 

Which shows that the list is clearly not sorted. Where am I mistaken?

+7
java
source share
2 answers

Your call to sort passes another comparator:

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

For this sorting, this PostingsEntryComparator replaces the "natural order" with score , as set by the PostingsEntry implementation of the Comparable<PostingsEntry> . Therefore, entries are compared by their docID . If you type docID instead of score , you will see that your list is ordered correctly according to identifiers.

Note. Subtracting the identifiers of the two compared items can lead to incorrect results due to integer overflow. Use Integer.compare , just as you used Double.compare in PostingsEntry.compareTo .

+11
source share

When you call

  Collections.sort(list, new PostingsEntryComparator()); 

you are sorting a PostingsEntryComparator that compares docID s.

If you want to sort by invoice, you need to use the Comparable implementation of your PostingsEntry , which you can do by calling Collections.sort() without passing a Comparator :

 Collections.sort(list); 
+7
source share

All Articles