Java Equals and Hashcode general Contract
Overiding BOTH, equals and hashcode method is not a common practice among java developers, but is strongly recommended in order to avoid the followings.
1) duplicate Objects in a set
2) list’s contains method returns false even you have added that object in the list
3) Can not find same content object in a hashtable even the contents of the objects are same
First thing first:
The first thing you must remember is when ever you override equals method, you must override the hashcode method as well.
The reason for doing so is the default implementation of equals method is to compares the memory addresses of the objects and if you override the equals() and you dont override hashcode you are violating the general contract for Object.hashCode, which can have unexpected consequences when your class is used with hash-based collections like hashmap and hashtable
The simplified version of General Contract for HashCode method
a) The hashcode must return the same integer value, if called multiple times on the same object, considering that the object properties are not modified.
b) If the equals method returns true for two objects then the hashCode method of the two objects must return the same integer value.
c) If two objects are not equal, there hashcode still can be the same but its a good practice producing distinct integer results for unequal objects becuase it may improve the performance of hashtables.
more to come when ever I got time/chance to write…