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
Are they Equal??true
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.
kundan sharma wrote:I have orverridden equals and hashcode method for my Emp class.
Actually, no, you haven't. You can only override a method which actually exists in the superclass. The superclass of your Emp class is Object, correct? And Object has an equals(Object) method, which you have overridden correctly. However it does not have a hashcode() method, as you could check by preceding your hashcode() method with the same "@Override" annotation you used for your equals(Object) method.
Check the documentation carefully. "hashcode" is not the correct spelling of the method you intended to override.