How to deny that a value is the same as the value in Java [integer. Min_value]

How are these values the same in Java?

-Integer.MIN_VALUE == Integer.MIN_VALUE

The values are:

-2147483648 : -2147483648

I try to compare it and return to reality [amazing!]

Solution

Yes, this is the expected behavior Int ranges from - 2147483648 to 2147483647

From JLS section 15.15 4 (emphasize my):

~Integer. MIN_ Value is integer MAX_ Value... When you add one, it overflows to integer MIN_ VALUE.

That's why when you implement an inversion comparator, you can't do this:

// BAD CODE!
public int compare(T x,T y) {
    return -originalComparator.compare(x,y);
}

Instead, use this:

// This is fine,assuming the comparator obeys its contract
public int compare(T x,T y) {
    return originalComparator.compare(y,x));
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>