Wednesday, February 20, 2013

Inserting Duplicate Values In Set ( java.util.Set)


Java.util.Set : as per definition, it is said that set contains the unique values. Now Q arises in mind how Set interface decides that the current value is duplicate. Lets see some scenarios:
1.      If you are inserting any numbers, its great it can directly say yeah this number I already have so it’s a duplicate number.
2.      If you are inserting any String, as String implement Comparable internally, Set still can determine that yes the String is Duplicate.
3.      Now Suppose you want to enter any custom object, like your employee class object, which  has many fields like name, id ,address. So in this case how our set decide which object is Duplicate.

Actually to determine duplicity it use two methods named equals() and hashcode(), if you can play with them, you can allow Set to contain duplicates.

Q. What is the significance of equals() and hashcode() method in Java Collections ? Why do we have to override the native implementation for these methods in some collections like HashMap?

Ans. let's see one example, in which we will override the equal() and hashcode() methods.
equal() returns boolean value, while hashcode() returns integer.

Code:

package inibm.collection;

import java.util.*;

/* Creating a custom Employee class with 2 fields name and id, we will see that even if two employees are having same id and name, still Set will add them into collection*/


class Employee{
  
      private int eid;
      private String ename;
     
      public Employee(int eid, String ename) {
            this.eid = eid;
            this.ename = ename;
      }

      @Override
      public String toString() {
            return "Employee [eid=" + eid + ", ename=" + ename + "]";
      }
     
      /* overriding equals method saying even if two objects are having same eid and ename still they are not equal, means you are giving your own definition of equals */
    
     public boolean equals(Object obj) {
            if(obj==null)
                  return false;
            if(obj==this)
                  return true;

     if( this.eid==((Employee)obj).eid && this.ename==((Employee)obj).ename)
                  return false;
            return false;
      }
     
/* overriding hashcode() method to generate hashcode based on its eid*/

     public int hashCode() {
            return this.eid +25;
      }
}

public class SetTest {

      public static void main(String[] args) {
            Set<Employee> test=new HashSet<Employee>();
            Employee t1=new Employee(1,"sushil");
            Employee t2=new Employee(1,"sushil");
           
            test.add(t1);
            test.add(t2);

            Iterator<Employee> its=test.iterator();
            while(its.hasNext())
           {
                 Employee value=(Employee)its.next();
                 System.out.println("Value :"+value);
           }
}}


Output :

Value :Employee [eid=1, ename=sushil]
Value :Employee [eid=1, ename=sushil]

2 Employee object in the Set containing the same values, clear cut violation of standards.


1 comment:

Unknown said...

In this case we are creating multiple Employee class object then officialy each Employee class object will hold own unique hashCose value.So, there is no need to override above euqals(),hashCode() method.