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;
}
}
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;
}
}