I'm being asked to investigate a bug as part of my internship. A piece of code is throwing
java.lang.IllegalArgumentException: Comparison method violates its general contract!
A custom Comparator
is comparing two custom classes by looking at long
member variables of said custom class:
return v1 > v2 ? -1 : v1 < v2 ? 1 : 0;
The equals
method for this custom class looks at a String
member variable of this custom class.
We're having a hell of a time reproducing the behavior.
My knee-jerk reaction was to replace the return statement in the custom Comparator
with return v2.compareTo(v1);
,
but my team is skeptical that this will address the problem.
Can anyone offer any insight?
Arrays.sort(anArray, new Comparator<ACustomClass>() {
@Override
public int compare(ACustomClass o1, ACustomClass o2) {
long v1 = o1.getALong();
long v2 = o2.getALong();
return v1 > v2 ? -1 : v1 < v2 ? 1 : 0;
}});