In Java with SonarQube, how to fix `Only the sign of the result should be examined`

Viewed 1478

I have the following line of code (where "next" is a BigDecimal):

if (next.compareTo(maximum) == 1) {
    maximum = next;
}

On the equality comparison, SonarQube gives me this warning:

Only the sign of the result should be examined.sonarqube-inject

What does it actually mean and how can I fix that ?

2 Answers

You should only test if it's greater than zero:

if (next.compareTo(maximum) > 0) {
                        maximum = next;
                    }

From the API docs of the compareTo Method:

Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

Sonar is suggesting to check the result of compareTo against 0, not if it returns directly 1, -1.

if (next.compareTo(maximum) >0) {
                        maximum = next;
                    }

You can find the reason for this suggestion in the compareTo() Javadoc

Returns: a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

Related