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,
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Shakil Pathan
Shakil is an experienced Groovy and Grails developer . He has also worked extensively on developing STB applications using NetGem .