A comparison method returns a difference of two numbers, which can overflow and flip the sign

tx0/java:compare-subtractionrecommendedwarningbug

What it finds

return this.size - other.size; in compareTo overflows when the two values are far apart: Integer.MAX_VALUE - (-1) wraps around to a negative number, and the larger value is reported as smaller. Integer.compare(this.size, other.size) compares without arithmetic.

Reported in compareTo and compare methods that return the difference of an int or long value and one of an unknown or the same type; differences of char, byte and short values cannot overflow and are left alone.

From the rule's source, compare_subtraction.rs.

Example from the rule's tests
import java.util.Comparator; class Item implements Comparable<Item> {  int size;  char grade;   @Override  public int compareTo(Item other) {    if (grade != other.grade) {      return grade - other.grade;    }    return size - other.size;tx0 reports: size - other.size can overflow and give the wrong sign  }   static final Comparator<Item> BY_SIZE = new Comparator<Item>() {    @Override    public int compare(Item a, Item b) {      return Integer.compare(a.size, b.size);    }  };}
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-subtraction" = "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-subtraction] reason="..."

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