HashSet contains duplicate entries in java

There are HashSet contains duplicate entries due to following reason :-

  • Here we are created User defined Employee object, for every object there are generated different hashcode so we put this hashcode in different buckets.
  • HashSet does not overridden the equals and hashCode methods,if you want remove duplicate object then we need to implement hashcode and equals method in 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;

	Employee(String name) {
		this.name = name;
    public String toString() {
		return name;

public class DuplicateSet {
	public static void main(String[] args) {
		Set<Employee> hs = new HashSet<Employee>();
		hs.add(new Employee("Vinay"));
		hs.add(new Employee("Pankaj"));
		hs.add(new Employee("Ajay"));
		hs.add(new Employee("Varun"));
		System.out.println("Total Employee Data :- " + hs);

Output :-
Total Employee Data :- [Ajay, Vinay, Pankaj, Varun]