What issues / pitfalls must be considered when overriding equals
and hashCode
?
Java – sues should be considered when overriding equals and hashCode in Java
equalshashcodejavaoverriding
Related Topic
- Java – a serialVersionUID and why should I use it
- Java – Difference between StringBuilder and StringBuffer
- Java – Why is Java Vector (and Stack) class considered obsolete or deprecated
- Java – How should equals and hashcode be implemented when using JPA and Hibernate
- Java – Comparing Java enum members: == or equals()
- Java – Overriding equals() & hashCode() in sub classes … considering super fields
- Java – need to override the equals and hashCode methods in Java
- Java – How default .equals and .hashCode will work for the classes
Best Answer
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.