Monday, January 17, 2011

When providing a user defined class to HashMap or HashTable what methods needs to be overridden?

You should override the equals() and hashCode() methods from the Object class. The default implementation of the equals() and hashcode(), which are inherited from the java.lang.Object uses an object instance’s memory location (e.g. MyEmployeeObject@8d52g38h). This can cause problems when two instances of the Employee objects have the
same id but the inherited equals() will return false because it uses the memory location, which is different for the two instances. Also the toString() method can be overridden to provide a proper string representation of your
object. Points to consider:

• If a class overrides equals(), it must override hashCode().
• If 2 objects are equal, then their hashCode values must be equal as well.
• If a field is not used in equals(), then it must not be used in hashCode().
• If it is accessed often, hashCode() is a candidate for caching to enhance performance.

1 comment: