How HashSet checks for duplicates ?

When you put an object into a HashSet , it uses hashcode value to determine where to put the object in the set. It also compares the objects hashcode value to other object’s hashcode in the hashset.
But two objects having same hashcode might not be equal. If the hashcode of two objects are equal then hashset uses equal() to see if the hashcode matched objects are really equal. And if they are equal the hashset knows that the new object is duplicate of something exist in the HashSet. And the add does not happen. The add() of hashcode returns false.

1 comment: