Inspectopedia Help

Suspicious 'Comparator.compare()' implementation

Reports problems in Comparator.compare() and Comparable.compareTo() implementations.

The following cases are reported:

  • A parameter is not used. Most likely this is a typo and the other parameter is compared with itself, or the method is not implemented correctly.

  • It's evident that the method does not return 0 for the same elements. Such a comparison method violates the contract and can produce unpredictable results when equal elements are encountered. In particular, sorting may fail with an exception on some data.

  • The comparison method never returns positive or negative value. To fulfill the contract, if the comparison method returns positive values, it should also return negative ones if arguments are supplied in reversed order.

  • The comparison method returns Integer.MIN_VALUE. While allowed by the contract, it may be error-prone, as some call sites may incorrectly try to invert the return value of the comparison method using the unary minus operator. The negated value of Integer.MIN_VALUE is Integer.MIN_VALUE.

Example:

Comparator<String> lambda = (a, b) -> a.length() > b.length() ? 0 : Math.random() > 0.5 ? -1 : 1;

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.

ComparatorMethodParameterNotUsed
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

Availability

By default bundled with

IntelliJ IDEA 2024.1, Qodana for JVM 2024.1,

Can be installed with plugin

Java, 241.18072

Last modified: 18 June 2024