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.
Default configuration
<module name="EqualsHashCode"/>
Examples
Example of incorrect code:
public class User {
private String name;
private int age;
@Override
public int hashCode() {
int result = 17;
result = 31 * result + name.hashCode();
result = 31 * result + age;
return result;
}
}
Example of correct code:
public class User {
private String name;
private int age;
@Override
public int hashCode() {
int result = 17;
result = 31 * result + name.hashCode();
result = 31 * result + age;
return result;
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof User)) {
return false;
}
User user = (User) o;
return user.name.equals(name) && user.age == age;
}
}
The contract of
equals()
andhashCode()
requires that equal objects have the same hashCode. Therefore, whenever you overrideequals()
you must overridehashCode()
to ensure that your class can be used in hash-based collections.Default configuration
Examples Example of incorrect code:
Example of correct code: