I am not exactly sure when do we need to implement equals() and hashCode() method? As far as I Understand, if we use a HashMap, and put some object of user defined class as key, then that class must implement both of the above methods or else we wont be able to retrieve the object for that key....
Above, i use an instance of class HashCodeExampleSimple as key in map.However, I dont see any issues when i try to retrieve the value based on the above keys...
Then please let me know when can the problem occurs and when do i need to implement hashcode() and equals() method
Someone says "Impossible is nothing". The man next him says "Let me see you licking your elbow tip!"
See..if two objects are equal then their hash code must be equal..thats why we are overrides hash code method when you overrides equals method.
Joined: Dec 20, 2007
thanks arvind but that doesnot exactly asnwer my question.....
What i want to know is that what if i dont implement any of these methods...like in the example mentioned in my first post...
I read that , every key in HashMap must implement both the methods(If iam interested to retrieve the object i.e value). I need more info on that
Joined: Dec 31, 2008
In Your example you are not overwriting any equals and hash code method.
You are creating three instance of HashCodeExampleSimple and putting into the Map....But what if any of two instances are equal.?
From our code they will added into the Map...that should not happen...!!!
thats why we are checking into the Equals that Before adding into the Map/Set they are equal OR not...also check the hash code ...
in hash code we are generating unique number that will same if two objects are equals ...thats why that equal object will not get added into Map or Set..
AS far your code what should happen if i change Code like this..at line No 17