I am trying to make a search auto-complete feature in an android app. There is list of business names and also a list business types that I am putting into one arraylist, scoring according to a fuzzy search algorithm, and then sorting the list based on the scores against the search term. I want business types that score the same as a business name to appear first. I wrap the instances of Business and BusinessType in this class as they are scored, add to list and then sort :
public class SearchMatch<T extends NameMatcher> implements Comparable<SearchMatch> {
public T data;
public int score;
public SearchMatch(T data, int score) {
this.data = data;
this.score = score;
}
@Override
public int compareTo(SearchMatch o) {
if(this.score == o.score && this.data instanceof BusinessType
&& o.data instanceof Business){
return -1;
}
return o.score - this.score;
}
}
... but this does not work. I get a "Comparison method violates its general contract." from Collections.sort - and nothing else in logcat.
I cant see what is wrong with it or how it violates transitivity (from other similar posts). The strange thing is if I return 1 instead of -1 I dont get the error but I get the wrong order of preference.
Thanks
Solved
public class SearchMatch<T extends NameMatcher> implements Comparable<SearchMatch> {
public final T data;
public final int score;
public SearchMatch(final T data,final int score) {
this.data = data;
this.score = score;
}
@Override
public int compareTo(SearchMatch o) {
if(this.score == o.score && this.data instanceof BusinessType
&& o.data instanceof Business){
return -1;
}
if(this.score == o.score && this.data instanceof Business
&& o.data instanceof BusinessType){
return 1;
}
return o.score - this.score;
}
}