在 Java 与 SonarQube 中,如何修复“只应检查结果的符号”

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

我有以下代码行(其中 "next" 是一个 BigDecimal):

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

关于相等比较,SonarQube 给我这个警告:

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

它到底是什么意思,我该如何解决?

您应该只测试它是否大于零:

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

来自 compareTo 方法的 API docs

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

Sonar 建议检查 compareTo 的结果是否为 0,如果是 returns 直接1,-1.

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

您可以在 compareTo() Javadoc

中找到此建议的原因

Returns:负整数、零或正整数,因为此对象小于、等于或大于指定对象。