The following lines:
ArrayList<ShowdownSingleValueVO> sortedValues = new ArrayList<>();
(...fill the array...)
Collections.sort(sortedValues);
Return the following exception: Comparison method violates its general contract!
I understand that this exception is typically generated when the comparison method is not properly implemented but, in my case, its implementation is fairly obvious:
public static class ShowdownSingleValueVO implements Comparable<ShowdownSingleValueVO>{
int hashValue;
byte showdownValue;
public ShowdownSingleValueVO(int hashValue, byte showdownValue) {
this.hashValue = hashValue;
this.showdownValue = showdownValue;
}
@Override
public int compareTo(ShowdownSingleValueVO o) {
return this.hashValue - o.hashValue;
}
}
As you can see, the objective is to have the values sorted by their hashValue attribute.
Any idea / hint on what I'm doing wrong would be greatly appreciated !
Thanks, Thomas
Most likely you are running into an int
overflow. Since hash codes could be arbitrarily large in magnitude, it is conceivable that subtraction would overflow for some pairs of values, producing a positive when subtracting two negative numbers.
Replace subtraction with the implementation from Integer
to fix this problem:
public int compareTo(ShowdownSingleValueVO o) {
return Integer.compare(this.hashValue, o.hashValue);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments