我有以下代码按降序对列表进行排序
List<Integer> list=Arrays.asList(Integer.MAX_VALUE, -1);
list.sort((x, y) -> y-x);
System.out.println(list)
结果是
[-1, 2147483647]
现在,我知道我不应该写 y-x,因为它会导致溢出问题。
但问题是为什么输出是这样的?我相信输出会是 [2147483647, -1]
因为 -1 - Integer.MAX_VALUE
是 -2147483648
,仍然是一个负整数,广告该操作似乎不受溢出问题的影响。
我做错了什么?
最佳答案
正如您在 Oracle's Object Ordening Java Tutorial 中所读到的那样靠近页面底部:
You might be tempted to replace the final return statement in the Comparator with the simpler:
return e1.number() - e2.number();
Don't do it unless you're absolutely sure no one will ever have a negative employee number! This trick does not work in general because the signed integer type is not big enough to represent the difference of two arbitrary signed integers. If i is a large positive integer and j is a large negative integer, i - j will overflow and will return a negative integer. The resulting comparator violates one of the four technical restrictions we keep talking about (transitivity) and produces horrible, subtle bugs. This is not a purely theoretical concern; people get burned by it.
这里描述的情况是OP遇到的情况:两个整数之间的差值大于Integer.MAX_VALUE
,因此在比较时会溢出,导致意外排序。
关于Java - List<Integer> 排序、比较器和溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45167365/