Can any one explain why this hashset is allowing duplcate objects? I have orverridden equals and hashcode method for my Emp class. Here are my two classes.
When I execute this program I get following result:
Are .hashCode Equals==true
Equals invoked
Are they Equal??true
HashSet Size--->>>2
This means hashcode for two references emp1 & emp2 are same i.e. 23
My Equlas method is also being invoked and as per this overridden equals method these two objects are equal. So logically if these two objects are equal, Hashset should not allow addition of emp2 and size should remain as 1 instead of 2.
Can somebody please explain if I am missing something?
As per my understanding, HashSet before adding any object calculates the hashcode of object being added and if it finds an identical hashcode in array of buckets, then only it invokes equals method to check the equality for each item present in that bucket present at that bucket for a given hashcode. If equals method returns true, then that object is not added else, it is added in the same bucket (corresponding to the hashcode) as another node in the linked list.
Please confirm my udnerstanding.
Kundan
[Added code tags - see UseCodeTags for details]