62,625
社区成员
发帖
与我相关
我的任务
分享import java.util.*;
/**
* @author :Liu Gui Jie
* @date :Created in 2019-04-22 12:34:21
* @description:
*/
public class Test {
public static void main(String[] args) {
//环境jdk 1.7
//几率报错
List<Integer> list = new ArrayList<>();
for (int a = 1; a < 500; a++) {
list.add(new Random().nextInt());
}
for (int a = 1; a < 10000; a++) {
Collections.sort(list, new Comparator<Integer>() {
// Comparator的实现必须保证以下几点(出自这儿):
// 1). sgn(compare(x, y)) == -sgn(compare(y, x))
// 2). (compare(x, y)>0) && (compare(y, z)>0) 意味着 compare(x, z)>0
// 3). compare(x, y)==0 意味着对于任意的z:sgn(compare(x, z))==sgn(compare(y, z)) 均成立
@Override
public int compare(Integer x, Integer y) {
//问题出现在这里 正确写法知道,想知道这个 x-y 为啥报错
// x > y ? 1 : -1 违反第一条
// x - y 违反了上面哪一条?
return x - y;
}
});
}
}
}Connected to the target VM, address: '127.0.0.1:49373', transport: 'socket'
Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeHi(TimSort.java:868)
at java.util.TimSort.mergeAt(TimSort.java:485)
at java.util.TimSort.mergeCollapse(TimSort.java:410)
at java.util.TimSort.sort(TimSort.java:214)
at java.util.TimSort.sort(TimSort.java:173)
at java.util.Arrays.sort(Arrays.java:659)
at java.util.Collections.sort(Collections.java:217)
at com.Test.main(Test.java:23)
Disconnected from the target VM, address: '127.0.0.1:49373', transport: 'socket'
Process finished with exit code 1