468
| The theory (for the language lawyers and the mathematically inclined):equals() (javadoc) must define an equality 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 of equals() , it must keep returning the same value).
The relation between the two methods is:
Whenever
a.equals(b) , then a.hashCode() must be same as b.hashCode() .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 compute hashCode() .
Use the excellent helper classes EqualsBuilder and HashCodeBuilder from the Apache Commons Langlibrary. An example:
Also remember:
When using a hash-based Collection or Map such as HashSet, LinkedHashSet, HashMap, Hashtable, orWeakHashMap, 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.
| ||||||||||||||||||||
|
Compilation of already published Articles/Ideas/Problems-Solutions which I faced or came across over the period of time. Largely a place for me to document it as note-to-self. Nothing serious. :)
Sunday, October 27, 2013
Subscribe to:
Post Comments (Atom)