Interview Question
Software Engineer / DevelopersActually, the .hashCode() method will have its default behavior, which in general produces different hashes for objects that compare equal. This is problematic for (e.g.) HashSet, which can mistakenly conclude that an object is not in the set when in fact there was an equal element in a bucket other than the one searched.
1)Assume, the equals method is overridden correctly and hashcode is left to default implementation. Now
EqualsOnlyObject o1 = new EqualsOnlyObject();
HashSet hs = new HashSet();
EqualsOnlyObject o2 = o1.clone(); //As per equals, o1 == o2 (but what abt hashcode?)
hs.Add(o1); //Added successfully
hs.Add(o2); //this too is added successfully(default hashcode is unique, as its mostly the memory address of the object)
PRINT hs.Count(); //should print "2"
2)But assume if the hashcode is overridden properly then hs.Add(o2) should not add the object "o2" since they are identical.
The sole purpose of hashcode() is to come up with efficient way of finding Hash buckets. Once a bucket is determined the overridden equals method can be used to retrieve that element.
- Amrut March 14, 2010Without hashcode method, all the elements can be inside a single bucket and hence result in inefficient hashes.