This content has been marked as final. Show 6 replies
bongale wrote:You need to override these methods whenever you stored your object in a collection like HashSet or HashMap.
I need one real time example so as to why i need to override equals and hashCode function.thanks for your early reply.
These collections classes depend on the fact that the objects that you put as a key in them must obey the hashCode and equal contract. You will get strange and unpredictable results at runtime if you do not obey the contract and try to store them in a collection.
Also see [http://java.dzone.com/articles/java-hashing|http://java.dzone.com/articles/java-hashing]
What about if I say, I have two persons with same name, age and address and when I say, two persons that means two different instances of person class, with all property values same inside.
Now what you will do to tell Java, if these two are really same objects.
Obviously java can't assume or go everytime to match all property itself to decide if they are same or different entities.
Here use of hashCode and equals comes in.
If you using Collections, it becomes necessary to provide correct hashCode and equals otherwise above mentioned issues will occur.