Java | Remove duplicate objects from Java Hashsets and Hashmap keys

|
| By Webner

In Java, a Hashset, theoretically, cannot contain any duplicate values but it is not valid when you store user defined objects in it. Same is true in case of Hashmap keys which supposedly cannot be duplicate. The reason is, how will Java interpreter know if our custom defined objects are equivalent or different? If we do not provide a way to the interpreter to detect that, it will allow duplicate objects. The solution can be achieved by overriding hashcode and equals methods in our custom class. Below is an example:

package duplicate;
import java.util.HashSet;
public class DuplicatesInHashSet {
public static void main(String[] args) {
HashSet set=new HashSet();
set.add(new item(3) );
set.add(new item(3));
set.add(new item(3));
System.out.println("Size of set "+set.size());
}
}
package duplicate;
public class item
{
private int id;
public int getId() {
return id;
}
public item(int id)
{
super();
this.id = id;
}
public void setId(int id) {
this.id = id;
}
}

Output : Size of set 3

In this example 3 objects with same id are inserted in a hashset without any problem. Now we will modify item class to implement equals and hashcode methods to make sure if 2 objects have same id then they are treated as same.

package duplicate;
public class item
{
private int id;
public int getId()
{
return id;
}
public item(int id)
{
super();
this.id = id;
}
public void setId(int id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
return this.id == ((item)obj).id;
}
@Override
public int hashCode()
{
return id;000000
}
}

Output :Size of set 1

Now you can see it gives size 1. It internally calls hashcode and equals methods to understand that all 3 items objects are actually same since they have same id value, so even if we execute 3 statements to insert 3 objects, it inserts only 1 object preventing duplicates.

Webner Solutions is a Software Development company focused on developing CRM apps (Salesforce, Zoho), LMS Apps (Moodle/Totara), Websites and Mobile apps. If you need Web development or any other software development assistance please contact us at webdevelopment@webners.com

Leave a Reply

Your email address will not be published. Required fields are marked *