The result of compareTo or compare is compared with 1 or -1

tx0/java:compare-to-constantrecommendedwarningbug

What it finds

a.compareTo(b) == 1 assumes a result that compareTo does not promise: it returns some negative number, zero or some positive number, and many implementations, such as that of String, return other values than -1 and 1. > 0 and < 0 test the order.

Reported are comparisons with == and != of the result of compareTo with one argument, or compare with two, against 1 or -1. BigInteger and BigDecimal promise exactly -1, 0 and 1, so calls on values whose type is known to be one of them, or that are computed from one by a chain of calls, are left alone.

From the rule's source, compare_to_constant.rs.

Example from the rule's tests
import java.math.BigInteger;import java.util.Comparator; class Order {  boolean before(String a, String b, Comparator<String> order, BigInteger x, BigInteger y) {    boolean r = a.compareTo(b) == -1;tx0 reports: assumes compareTo returns exactly -1    r = order.compare(a, b) != 1;tx0 reports: assumes compare returns exactly 1    r = 1 == a.compareTo(b);tx0 reports: assumes compareTo returns exactly 1    r = a.compareTo(b) < 0;    r = a.compareTo(b) == 0;    r = x.compareTo(y) == 1;    r = x.add(y).abs().compareTo(y) == -1;    return r;  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/java:compare-to-constant" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/java:compare-to-constant] reason="..."

tx0 explain tx0/java:compare-to-constant shows the same in the terminal. Found a false positive? Report it.