posted 9 years ago
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]