Forums Register Login

Working of HashSet

+Pie Number of slices to send: Send
Hello,
I have difficulty in understanding the behaviour of Hashset in the following two scenarios.
1.I have overridden the equals method such that it always returns true and kept the default hashCode method.
2.I have overridden the equals method such that it always returns true and also the hashCode method such that it always returns single number.
I have following results respectively
a.Accepts multiple objects of same class type.
b.Accepts single object of same class type even when multiple are inserted.
Also the documentation for Set mentions "sets contain no pair of elements e1 and e2 such that e1.equals(e2)".So here i am unable to understand the behaviour of hashset for case 1 & 2 that is even when equals returns true why does it accept same type of multiple objects.
Following is the code:

Output:
[12, 7, 13, 14, 10, 6, 19, 5, 9, 11, 18, 17, 15, 16, 4, 8, 2]
+Pie Number of slices to send: Send
The hashcode method is not independent of the equals method. Check the Javadoc for hashcode and you will see that objects that are equal according to equals must have the same hashcode. You have broken that contract in your first scenario so the Hashset is getting confused.

Hashset works by creating a series of 'buckets'. It uses the hashcode to decide which bucket an object belongs in, and then it uses equals to see if the new object equals any objects already in that bucket.

In your first scenario your objects all have different hashcodes so they get put into different buckets. The equals method never even gets called.

In your second scenario your objects are all equal according to the equals method and they all have the same hashcode, so the hashset will only store one of them.
+Pie Number of slices to send: Send
Thanks a lot Mike!!!
I now get the concept.
A "dutch baby" is not a baby. But this tiny ad is baby sized:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 599 times.
Similar Threads
Using java.util.HashSet for Custom Class
Natural Ordering in HashSet for objects
overriding hashcode and equals method internal work flow
help sought in Collections ?
Why HashSet is adding duplicates even if I get same hashcode for two obects & passes true fromequals
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 09:09:56.