I am trying to implement the comparable interface in Java for an object that I need to sort by two different columns/variables. I tried multiple approaches, and this one is the best so far:
public int compareTo(Object o) {
Match m = (Match)o;
int diff = m.matches - matches;
if (diff == 0) {
if (distance > m.distance) {
return 1;
} else if (distance < m.distance) {
return -1;
} else {
return 0;
}
} else {
return diff;
}
}
but it still fails with
java.lang.IllegalArgumentException: Comparison method violates its general contract!
Any ideas what I'm doing wrong?
Side note 1: NPEs/ClassCastExceptions are expected, if o is null or of an unsuitable class - that is not the issue here.
Side note 2: I know about the change in the sorting algorithm in JDK 1.7, but I don't really see where I'm violating the contract here. So turning off the exception seems like the wrong solution.