Can I assume that, because I didn't override the hashCode() of Object class in Employee class, LinkedHashSet is allowing duplicates.
Well it depends on what you define as duplicates. Fot the HashSet both your Employee instances Vasu are completely different objects. If you don't want these objects to be treated differently you have to override the java.lang.Object's default equals() implementation (and don't forget to override hashCode() as well!). [ October 15, 2008: Message edited by: Thomas Thevis ]
Yes you understood it true ! you must override both hashcode and equals method
Because Java cannot know anything about your user defined objects so you should present the equality for them. So, Sets cannot know anything your object than it allowes dublicates of object in it. Normally for wrappers (because they override equals,hashcode well) they won't add in Set with dublicates so you must override and tell the compiler what is the rule of equality otherwise your Set won't work as you expect
I am sharing my current thinking here. If it is wrong, please tell me so I can correct my thinking.
The way it looks to me, Hash based collections store things by using "hash buckets", the different hash values to detect difference on a coarse scale.
Hashing is implemented by having a certain number of hash "buckets" in which to collect objects. When you add a new element to a HashSet, the first thing add() looks at is the hashCode(). If it is different from all others stored there then there is no need to look at the equals() method at all. Since the hashCode is unique then it can't possibly be equal to anything currently IN the container. However, if the hashCode matches THEN add() calls the equals() method. If it returns false, then add() goes ahead and adds the element because it IS unique. If equals() returns true, then add() does NOT add this element becuase it's "equal" is already in the list.
With the above in mind, if you do not override hashCode() then the hashCode() that is inherited from Object will always be unique. No two objects will ever have an equal hashCode so the container will always add the new element. It won't even look at the equals() method.
Man.....I hope this makes sense....
SCJP - 86% - June 11, 2009
Joined: Sep 02, 2008
good explanation. I think you're right.
Joined: Mar 29, 2007
Thanks for clearing my doubt. Thanks for your detailed explanation. Have a wonderful day ahead!