Forums Register Login

Set Duplicates

+Pie Number of slices to send: Send
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 will suppress my every urge. But not this shameless plug:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


Reply locked
This thread has been viewed 855 times.
Similar Threads
overriding hashcode and equals method internal work flow
Set Duplicates
List Vs Set
HashMap entries with duplicate keys...
hashCode() - why?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 03:01:47.