Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
    Bookmark Topic Watch Topic
  • New Topic

Set Duplicates

 
vimal kumar
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Report post to moderator
I'm adding the Employee objects in the Set collection. I have overrided the equals, hashCode and toString method of the Employee class. If there are two Employee instances with the same name, it won't be added to the Set since it won't allow duplicates. The output of the below program is [vimal] as expected.

However, if we replace the equals method of the Employee class as follows where the Employee class parameter is replaced by Object class parameter, which is a correct override, it results in output [vimal, vimal].

Replaced equals method:

public boolean equals(Employee x)
{

if(empname. equals(x.empname))

return true;
else
return false;
}




I don't know the reason behind this output.

import java.util.Set;
import java.util.HashSet;
class SetDemo
{
public static void main(String[] a)
{
Employee e = new Employee("vimal");
Employee e2 = new Employee("vimal");

Set ll = new HashSet();

ll.add(e);
ll.add(e2);

System.out.println(ll);
}

}

class Employee
{
String empname;

Employee(String x)
{
empname = x;
}
public String toString()
{
return empname;

}
public int hashCode()
{
return empname.length();

}
public boolean equals(Object x)
{

if(x instanceof Employee && empname. equals(((Employee)x).empname))

return true;
else
return false;
}


}
 
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic
Boost this thread!