Java


JAVA.COMPARE.CTO.NONOBJ : Non-Object compareTo Parameter (Java)

Summary

compareTo() is defined for a non-java.lang.Object argument but the comparable class is raw.

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 Non-Object compareTo Parameter (Java)
Significance reliability
Mnemonic JAVA.COMPARE.CTO.NONOBJ
Categories
CWE CWE:1097 Persistent Storable Data Element without Associated Comparison Control Element
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="Non-Object compareTo Parameter (Java)"

Example

Consider the following program:

public abstract class CompareTo implements Comparable {
  private static int nextId;
  private final int id = nextId++;

  public final int compareTo(CompareTo other) { // "Non-Object compareTo Parameter (Java)" warning issued here
    return id - other.id;
  }
}

In this example, the programmer should either make CompareTo implement Comparable<CompareTo> or change the signature of the method into compareTo(Object) and check the type of the actual parameter inside the method's body.

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.