Importance Of HashCode And Equals In Java Collections

Posted By : Shakil Pathan | 28-Feb-2018

Hi Guys,

In this blog, I am going to explain you about the importance of hashCode() and equals() in Java Collections.

The methods hashCode() and equals() play a unique role for the objects which you insert into a Java collection.

The method equals() is used in most collections to check if a collection contains a given object. 

 

List<string> list1 = new ArrayList<>();
list1.add("abc");

boolean containsABC = list1.contains("abc");

 

In the above code, the ArrayList loop over all its elements and execute "abc".equals(object) to check if the object is equal to the parameter object "abc". This is the String.equals() method implementation which checks if two strings are equal or not.

For removing elements from a collection the equals() method is also used .

 

List<string> list1 = new ArrayList<>();
list1.add("abc");

boolean removedABC = list1.remove("abc");

 

The ArrayList again loop over all its elements and execute "abc".equals(object) to check if the object is equal to the parameter object "abc". The first element it finds in the ArrayList that is equal to the given parameter "abc" is removed by this.

 

The hashCode() method of the objects is used when you insert them into a HashTable, HashMap or HashSet. When inserting any object into a HashMap you use a key. The hashcode of the key is calculated and used to check where to store this object internally. When you need to lookup for an object in a HashMap you also use a key. The hash code of this key is calculated first and used to check where to search for the object.

 

Hope it helps you to understand the importance of hashCode and equals methods in Java Collections.

Thanks,

About Author

Author Image
Shakil Pathan

Shakil is an experienced Groovy and Grails developer . He has also worked extensively on developing STB applications using NetGem .

Request for Proposal

Name is required

Comment is required

Sending message..