Search code examples
javafindbugscompareto

FindBugs - how to solve EQ_COMPARETO_USE_OBJECT_EQUALS


I am clueless here...

 1: private static class ForeignKeyConstraint implements Comparable<ForeignKeyConstraint> {
 2: String tableName;
 3: String fkFieldName;
 4: 
 5: public int compareTo(ForeignKeyConstraint o) {
 6:    if (this.tableName.compareTo(o.tableName) == 0) {
 7:            return this.fkFieldName.compareTo(o.fkFieldName);
 8:        }
 9:        return this.tableName.compareTo(o.tableName);
10:    }
11: }

In line 6 I get from FindBugs: Bug: net.blabla.SqlFixer$ForeignKeyConstraint defines compareTo(SqlFixer$ForeignKeyConstraint) and uses Object.equals()

Link to definition

I don't know how to correct this.


Solution

  • This errors means that you're not overriding equals in ForeignKeyConstraint (and thus inheriting the equals from Object) so the following is not true (from the javadoc of compareTo):

    It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."

    To fix the FindBugs check, override equals - and hashCode - if it makes sense which is generally the case (or exclude the check for this class and document that your class violates this condition using the suggested note).