Java


JAVA.COMPARE.CTO.NONCOMP : compareTo in Non-Comparable Class (Java)

Summary

compareTo() is defined in a class that is not an instance of java.lang.Comparable.

A class C that implements the raw interface java.lang.Comparable must implement the compareTo(Object) method. If C is made to implement the non-raw interface java.lang.Comparable<C>, then it must implement the compareTo(C) method instead.

Moreover, it is good practice to make compareTo() consistent with equals(): if the comparison of two objects yields 0, then they should be equal. The validity of this implication is in general undecidable. There are, however, frequent situations when, typically, this implication does not hold. An example is when equals() is inherited from java.lang.Object.

This checker verifies that compareTo(Object) is defined for classes implementing the raw java.lang.Comparable interface, instead of the (possibly more logical) method compareTo(C). Moreover, it verifies the consistency of compareTo() wrt equals().

Inconsistent definitions of compareTo()/equals() induce unexpected behaviors when objects are put inside most SortedSet classes of the standard Java library.

Properties

Class Name compareTo in Non-Comparable Class (Java)
Significance reliability
Mnemonic JAVA.COMPARE.CTO.NONCOMP
Categories
CWE CWE:1076 Insufficient Adherence to Expected Conventions
Availability Available for Java only.
Enabling Checks for this warning class are enabled by default. To disable them, add the following WARNING_FILTER rule to the project configuration file.
WARNING_FILTER += discard class="compareTo in Non-Comparable Class (Java)"

Example

public class MyClass {

  public int compareTo(MyClass other) { // "compareTo in Non-Comparable Class (Java)" warning issued ehre
      //...
      }
        
  //...
}

To resolve this, ensure that MyClass implements the java.lang.Comparable interface.

public class MyClass implements Comparable<MyClass> {

  public int compareTo(MyClass other) {
      //...
  }
  //...
}        

Resolution

Use the non-raw interface java.lang.Comparable<C>; make equals() consistent with compareTo(). In most cases, this just amounts to providing the missing definition of equals().

Relevant Configuration File Parameters

The following configuration file parameters affect checks for this warning class.