以下程序抛出以下异常:
java.lang.IllegalArgumentException: Comparison method violates its general contract!
Run Code Online (Sandbox Code Playgroud)
我理解了这个问题Comparator.请参阅无法复制:"比较方法违反了其总合同!"
我不明白为什么只有List32或更大的s 才会失败.谁能解释一下?
class Experiment {
private static final class MyInteger {
private final Integer num;
MyInteger(Integer num) {
this.num = num;
}
}
private static final Comparator<MyInteger> COMPARATOR = (r1, r2) -> {
if (r1.num == null || r2.num == null)
return 0;
return Integer.compare(r1.num, r2.num);
};
public static void main(String[] args) {
MyInteger[] array = {new MyInteger(0), new MyInteger(1), new MyInteger(null)};
Random random = new …Run Code Online (Sandbox Code Playgroud)