Sunday, March 2, 2008

Java 1.5: Generics and Collections- equals() and hashCode()

  1. The default implementation of equals() method from Object class uses == operator for comparison. So if you don't override equals appropriately in your class, you can not use objects of your class as keys in a hashtable, or for building sets of objects such that there are no conceptual duplicates.
  2. If two objects are equal (by virtue of the equals() method returning true for them), their hashcodes (as returned by the method hasCode()) must be equal too. Otherwise, those objects can not be used in a collection which uses hashing (like HashMap or HashSet)
  3. Do not use transient variables in hasCode() and equals() overrides.

No comments: