Thursday, January 28, 2016

How avoid duplicate user defined object in HashSet

For avoiding duplicate user defined object we need to implement the hashCode and equals method

import java.util.HashSet;
import java.util.Set;

class Employee
{
    int id;
    String name;
    Employee(int id,String name)
    {
        this.id=id;
        this.name=name;
    }
    public int getId()
    {
        return id;
    }
    public String getName()
    {
        return name;
    }

    public int hashCode()
    {
        System.out.println("In hashcode");
        int hashcode = 0;
        hashcode = id*3; //use any prime number
        hashcode += name.hashCode();
        return hashcode;
    }

   public boolean equals(Object obj)
   {
        System.out.println("In equals");
        if (obj instanceof Employee) 
        {
            Employee e = (Employee) obj;
            return (e.name.equals(this.name) && e.id == this.id);
        }
        else 
        {
            return false;
        }
    }
}

  public class HelloWorld
  {
       public static void main(String []args){
       Employee e1=new Employee(1,"Ramesh");
       Employee e2=new Employee(1,"Ramesh");
       Set<Employee> set=new HashSet<Employee>();
       set.add(e1);
       set.add(e2);
       System.out.println("Size = "+set.size());
   }
}

***
Suppose we want to add object based on name only -

        Employee e1=new Employee(1,"Ramesh");
        Employee e2=new Employee(2,"Ramesh");

Here name is same but id is different so how we will avoid this type of duplicate object based on name -

Only hashCode and equals method need to update-

public int hashCode()
 {
        System.out.println("In hashcode");
        int hashcode = 0;
        // only name hashCode require
        hashcode += name.hashCode();
        return hashcode;
 }
   
   public boolean equals(Object obj)
   {
        System.out.println("In equals");
        if (obj instanceof Employee) 
        {
            Employee e = (Employee) obj;
            return (e.name.equals(this.name)); // no need to compare id
        } 
        else
        {
            return false;
        }
    }