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

Leave a comment

Hey!

I’m Bedrock. Discover the ultimate Minetest resource – your go-to guide for expert tutorials, stunning mods, and exclusive stories. Elevate your game with insider knowledge and tips from seasoned Minetest enthusiasts.

Join the club

Stay updated with our latest tips and other news by joining our newsletter.