Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why compareTo should not return Integer.MIN_VALUE

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading