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:

public static class Example1 {
    public int hashCode() {
        // code
    }
    public boolean equals(String o) { // violation, overloaded implementation of 'equals'
        // code
    }
}
public static class Example2 {
    public boolean equals(Object o) { // violation, no 'hashCode'
        // code
    }
    public boolean equals(String o) {
        // code
    }
}
public static class Example3 {
    public int hashCode() {
        // code
    }
    public boolean equals(Object o) { // OK
        // code
    }
    public boolean equals(String o) {
        // code
    }
}
public static class Example4 {
    public int hashCode() {
        // code
    }
    public boolean equals(java.lang.Object o) { // OK
        // code
   }
}
public static class Example5 {
    public static int hashCode(int i) {
        // code
    }
    public boolean equals(Object o) { // violation, overloaded implementation of 'hashCode'
        // code
    }
}
public static class Example6 {
    public int hashCode() { // violation, overloaded implementation of 'equals'
        // code
    }
    public static boolean equals(Object o, Object o2) {
        // code
    }
}
        

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