Java - List<Integer> sort, comparator and overflow

Viewed 997

I've the following code that sorts a list in a descending order

List<Integer> list=Arrays.asList(Integer.MAX_VALUE, -1);
list.sort((x, y) -> y-x);
System.out.println(list)

The result is

[-1, 2147483647]

Now, I know that I should not write y-x because it can cause overflow problem.

But the question is why is the output that? I believed the output would be [2147483647, -1] because -1 - Integer.MAX_VALUE is -2147483648, still a negative integer, ad the operation seems not be affected by overflow problem. What I did wrong?

3 Answers
Related