Java – Using HashTable Without Overriding hashCode()

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 to HashTable 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 the GetHashCode() method and then goes through a list using the Equals() 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 the HashTable.

In general, you want to make sure of two things when implementing hash codes:

  • If A.Equals(B) then A.GetHashCode()==B.GetHashCode()
  • Try to get a distribution of hash codes properly spread to get the maximum efficiency from the hash table (if too few hash codes are possible, you'll end up searching a list).