This content has been marked as final. Show 4 replies
What you use in the hashCode() algorithm is entirely up to you. So asking why it does or doesn't do something specific doesn't make any sense.
the one thing you need to be aware of when using the id in the hashCode (which is generally a good idea), is that new (not yet persisted) objects are kind of fragile. often the object id will not be assigned until the object has been persisted. so, you cannot put the object into a HashSet (or use its hashcode in any meaningful way) until it has first been persisted. as long as you take care of that, then using the id in the hashcode should be just fine.
Set will store only 1 element because hashCode for both y1 and y2 will be same
A Set can store many elements with the same hashCode. HashCode is not unique.
821046 wrote:As per API, "sets contain no pair of elements e1 and e2 such that e1.equals(e2)". Because of the equals() method, we also require a proper implementation of the hashCode() method.
As per the Java API contract, to store elements properly inside Set, we should have correct implementation of hashCode() method.
Set will store only 1 element because hashCode for both y1 and y2 will be same i.e 00047As jverd pointed out, only if you have respected the contract of both equals and the hashCode methods, will Set store the elements as expected. Only with the hashCode() it cannot be achieved.