How can these values be same in java?
-Integer.MIN_VALUE == Integer.MIN_VALUE
values are:
-2147483648 : -2147483648
i tried comparing it and returns true [Amazing!]
Yes, that's expected behaviour. The range of int is -2147483648 to +2147483647.
From the JLS section 15.15.4 (emphasis mine):
For integer values, negation is the same as subtraction from zero. The Java programming language uses two's-complement representation for integers, and the range of two's-complement values is not symmetric, so negation of the maximum negative
intorlongresults in that same maximum negative number. Overflow occurs in this case, but no exception is thrown. For all integer valuesx,-xequals(~x)+1.
~Integer.MIN_VALUE is Integer.MAX_VALUE... and when you add one, it overlows to Integer.MIN_VALUE.
This is why when you implement a reversing comparator, you mustn'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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With