Delete duplicate user defined object from LinkedHashSet

Q.  Write a program to delete duplicate user defined object from the LinkedHashSet.

Answer:

In this example, we find the duplicate object from the LinkedHashSet. There is an employee class, which has name and id.

Employee.java

class Employee
{
    private String name;
    private int id;
     
    public Employee(String name, int id)
    {
        this.name = name;
        this.id = id;
    }
     
    public int hashCode()
    {
        System.out.println("In hashcode method");
        int hashcode = 0;
        return hashcode;
    }     
    public boolean equals(Object obj)
    {
        System.out.println("In equals method");
        if (obj instanceof Employee)
        {
            Employee emp = (Employee) obj;
            return true;
        }
        else
        {
            return false;
        }
    }     
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }     
    public String toString()
    {
        return "Employee Id: "+id+"  Name: "+name;
    }
}


Duplicate_Value.java

import java.util.LinkedHashSet;
public class Duplicate_Value
{
    public static void main(String a[])
    {
        LinkedHashSet<Employee> lhm = new LinkedHashSet<Employee>();
        lhm.add(new Employee("John", 1020));
        lhm.add(new Employee("Ravi", 1040));
        lhm.add(new Employee("Jaya", 1030));
        for(Employee emp:lhm)
        {
            System.out.println(emp);
        }
        Employee duplicate = new Employee("John", 1020);
        System.out.println("Inserting duplicate record...");
        lhm.add(duplicate);
        System.out.println("After insertion:");
        for(Employee emp:lhm)
        {
            System.out.println(emp);
        }
    }
}


Output:

duplicate record