What is the importance of hashcode() and equals() methods?

HashMap uses the key object hashCode() and equals methods to determine the index to put the key-value pair. The methods are also used when we try to get the value from HashMap. If these methods are not implemented correctly, two different keys might produce the same hasCode() and equals() output and in that case, rather than storing it on different location, HashMap will consider the same and override them.

Similarly all collection classes that doesn’t store the duplicate data use hashCode() and equals() to find the duplicates, so it is very important to implement them correctly.

if (obj1.equals(obj2)), then obj1.hashCode() == obj2.hasCode() should always be true
if obj1.hashCode() == obj2.hasCode() is true it doesn't mean that obj1.equals(obj2) is true
Ramesh Kumar S avatar

Posted by

Leave a comment