aspose file tools*
The moose likes Certification Results and the fly likes Set Duplicates Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Certification Results
Reply locked New topic
Author

Set Duplicates

vimal kumar
Greenhorn

Joined: Aug 16, 2006
Posts: 6
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;
}


}
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Set Duplicates