Learn why does HashSet allow duplicate objects in Java and how overriding equals() and hashCode() prevents duplicate entries.
A HashSet does not allow duplicate elements. However, when storing user-defined objects, HashSet relies on the equals() and hashCode() methods to determine whether two objects are equal.
In this example, the Employee class does not override the equals() and hashcode() methods. As a result, each Employee object is treated as a unique object, even if the employee names are the same. Therefore, HashSet stores them as separate entries.
To prevent duplicate Employee objects in a HashSet, override both the equals() and hashCode() methods in the Employee class.
equals() method :- public boolean equals (Object obj)
hashCode() Method :- public int hashCode()
import java.util.HashSet;
import java.util.Set;
class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
public class DuplicateSet {
public static void main(String[] args) {
Set hs = new HashSet();
hs.add(new Employee("Vinay"));
hs.add(new Employee("Pankaj"));
hs.add(new Employee("Ajay"));
hs.add(new Employee("Varun"));
hs.add(new Employee("Vinay"));
System.out.println("Total Employee Data :- " + hs);
}
}
Output :-
Total Employee Data :- [Vinay, Pankaj, Ajay, Varun, Vinay]
Java Example Without equals() and hashCode()
Student class does not override the equals() and hashCode() methods. Without these methods, HashSet cannot determine whether two objects contain the same data and treats each object as unique.
import java.util.HashSet;
import java.util.Set;
class Student {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return id + " - " + name;
}
}
public class HashSetDuplicateDemo {
public static void main(String[] args) {
Set students = new HashSet();
students.add(new Student(101, "Rahul"));
students.add(new Student(102, "Amit"));
students.add(new Student(101, "Rahul"));
System.out.println(students);
}
}
Output :-
[101 – Rahul, 102 – Amit, 101 – Rahul]