Today I was asked this question during an interview:
What will happen if we do not override the
hashcode
method for our
class, then add it toHashTable
and then try to get objects?
What could go wrong?
collectionshashingjava
Today I was asked this question during an interview:
What will happen if we do not override the
hashcode
method for our
class, then add it toHashTable
and then try to get objects?
What could go wrong?
Best Answer
The idea with a
HashTable
when you try retrieving an object is that the data structure computes the hash code of the object using theGetHashCode()
method and then goes through a list using theEquals()
method.With default
GetHashCode()
implementation, two perfectly similar objects might end up yielding different hash codes which means that if you do not use the exact same instance, you will never find the your object in theHashTable
.In general, you want to make sure of two things when implementing hash codes:
A.Equals(B)
thenA.GetHashCode()==B.GetHashCode()