Synopsis: | Ensure you override both equals() and hashCode() |
Language: | Java |
Severity Level: | 2 |
Category: | Basic |
Description: |
Override both public boolean Object.equals(Object other), and public int Object.hashCode(), or override neither. Even if you are inheriting a hashCode() from a parent class, consider implementing hashCode and explicitly delegating to your superclass.// this is bad public class Bar { public boolean equals(Object o) { // do some comparison } } // and so is this public class Baz { public int hashCode() { // return some hash value } } // this is OK public class Foo { public boolean equals(Object other) { // do some comparison } public int hashCode() { // return some hash value } } Justification: “You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object.hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.” from Effective Java, by Joshua Bloch. If two objects are equal according to the {@code equals(Object)} method, then calling the {@code hashCode} method on each of the two objects must produce the same integer result. So, implementing an equals() method comparing 2 members, and then implementing a hashCode() which only calls super.hashCode() is just as bad. |