I am using SonarQube. There is a rule against java language:
It is the sign, rather than the magnitude of the value returned from
compareTo that matters. Returning Integer.MIN_VALUE does not convey a
higher degree of inequality, and doing so can cause errors because the
return value of compareTo is sometimes inversed, with the expectation
that negative values become positive. However, inversing
Integer.MIN_VALUE yields Integer.MIN_VALUE rather than
Integer.MAX_VALUE.
The problem is SonarQube consider this a bug, not code smell. Under what circumstances would this cause an error?
Can anyone give a example ?
>Solution :
the reason is here:
Integer a = -1;
Integer b = Integer.MIN_VALUE;
System.out.println(b); // -2147483648
System.out.println(-b); // -2147483648
System.out.println(a); // -1
System.out.println(-a); // 1
If you want to use the result of compareTo to judge, for example:
Integer a = x.compareTo(y)
if(-a > 0) {
//do something
}
If the return value of compareTo is Integer.MIN_VALUE, then the value of -a is equal to the value of a both are -2147483648, so the result is wrong