Inspectopedia 2024.3 Help

Subtraction in 'compareTo()'

Reports subtraction in compareTo() methods and methods implementing java.util.Comparator.compare().

While it is a common idiom to use the results of integer subtraction as the result of a compareTo() method, this construct may cause subtle and difficult bugs in cases of integer overflow. Comparing the integer values directly and returning -1, 0, or 1 is a better practice in most cases.

Subtraction on floating point values that is immediately cast to integral type is also reported because precision loss is possible due to rounding.

The inspection doesn't report when it's statically determined that value ranges are limited, and overflow never occurs. Additionally, subtraction on int numbers greater than or equal to 0 will never overflow. Therefore, this inspection tries not to warn in those cases.

Methods that always return zero or greater can be marked with the javax.annotation.Nonnegative annotation or specified in this inspection's options.

Example:

class DoubleHolder implements Comparable<DoubleHolder> { double d; public int compareTo(DoubleHolder that) { return (int)(this.d - that.d); } }

A no-warning example because String.length() is known to be non-negative:

class A implements Comparable<A> { final String s = ""; public int compareTo(A a) { return s.length() - a.s.length(); } }

Locating this inspection

By ID

Can be used to locate inspection in e.g. Qodana configuration files, where you can quickly enable or disable it, or adjust its settings.

SubtractionInCompareTo
Via Settings dialog

Path to the inspection settings via IntelliJ Platform IDE Settings dialog, when you need to adjust inspection settings directly from your IDE.

Settings or Preferences | Editor | Inspections | Java | Probable bugs

Use the options to list methods that are safe to use inside a subtraction. Methods are safe when they return an int value that is always greater than or equal to 0.

Inspection options

Here you can find the description of settings available for the Subtraction in 'compareTo()' inspection, and the reference of their default values.

Inspection Details

By default bundled with:

IntelliJ IDEA 2024.3, Qodana for JVM 2024.3,

Can be installed with plugin:

Java, 243.23126

Last modified: 03 December 2024