What issues / pitfalls must be considered when overriding equals and hashCode?
What issues / pitfalls must be considered when overriding equals and hashCode ?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The theory (for the language lawyers and the mathematically inclined):
equals()(javadoc) must define an equivalence relation (it must be reflexive, symmetric, and transitive). In addition, it must be consistent (if the objects are not modified, then it must keep returning the same value). Furthermore,o.equals(null)must always return false.hashCode()(javadoc) must also be consistent (if the object is not modified in terms ofequals(), it must keep returning the same value).The relation between the two methods is:
In practice:
If you override one, then you should override the other.
Use the same set of fields that you use to compute
equals()to computehashCode().Use the excellent helper classes EqualsBuilder and HashCodeBuilder from the Apache Commons Lang library. An example:
Also remember:
When using a hash-based Collection or Map such as HashSet, LinkedHashSet, HashMap, Hashtable, or WeakHashMap, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, which has also other benefits.