[英]Java sort throws java.lang.IllegalArgumentException: Comparison method violates its general contract
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. 如您所见,目标是使值按其hashValue属性排序。
Any idea / hint on what I'm doing wrong would be greatly appreciated ! 任何关于我做错的想法/暗示都将不胜感激!
Thanks, Thomas 谢谢,托马斯
Most likely you are running into an int
overflow. 很可能你遇到了
int
溢出。 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: 用
Integer
的实现替换减法来解决此问题:
public int compareTo(ShowdownSingleValueVO o) {
return Integer.compare(this.hashValue, o.hashValue);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.