EqualsHashCode

Since Checkstyle 3.0

Description

Checks that classes that either override equals() or hashCode() also overrides the other. This check only verifies that the method declarations match Object.equals(Object) and Object.hashCode() exactly to be considered an override. This check does not verify invalid method names, parameters other than Object, or anything else.

Rationale: The contract of equals() and hashCode() requires that equal objects have the same hashCode. Therefore, whenever you override equals() you must override hashCode() to ensure that your class can be used in hash-based collections.

Examples

To configure the check:

<module name="Checker">
  <module name="TreeWalker">
    <module name="EqualsHashCode"/>
  </module>
</module>
        

Example:

class Example1 {
  public int hashCode() { // violation, no valid 'equals'
    return 0;
  }
  public boolean equals(String o) { return false; }
}

class ExampleNoHashCode {
  public boolean equals(Object o) { // violation, no 'hashCode'
    return false;
  }
  public boolean equals(String o) { return false; }
}

class ExampleBothMethods1 {
  public int hashCode() { return 0; }
  public boolean equals(Object o) { // ok, both methods exist
    return false;
  }
  public boolean equals(String o) { return false; }
}

class ExampleBothMethods2 {
  public int hashCode() { return 0; }
  public boolean equals(java.lang.Object o) { // ok, both methods exist
    return false;
  }
}

class ExampleNoValidHashCode {
  public static int hashCode(int i) { return 0; }
  public boolean equals(Object o) { // violation, no valid 'hashCode'
    return false;
  }
}

class ExampleNoValidEquals {
  public int hashCode() { // violation, no valid 'equals'
    return 0;
  }
  public static boolean equals(Object o, Object o2) { return false; }
}
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker