Java - List<Integer> 排序、比较器和溢出

标签 java overflow comparator

我有以下代码按降序对列表进行排序

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/

相关文章:

java - 如何使用java验证html? jsoup 库出现问题

java - 与等效的 Calendar 代码相比,生成的 java.time 代码是否具有更多代码语句

html - 宽位置 :fixed element won't stay inside scrollable container

java - 为什么我的 CompareTo 会因一般契约(Contract)违规错误而崩溃?

java - 集合与扭曲 Java 的交集

java - 如何让 servlet 过滤器在 Tomcat 中的应用程序启动时停止加载?

css - 在代码中,为什么删除溢出 :hidden; from ul in css style, 会隐藏菜单?

menu - 带有 overflow-x 的水平菜单 :auto

java - 不能在 Comparator<String> 中使用静态 List<String>

java - java中如何实现父类(super class)和子类的Comparator