I have hashset whare i will store set to objects and i want to find particular object, in this case why do i need to override the hashcode and equals method which i read from below example
public class Emp
{
private int age ;
public Emp( int age )
{
super();
this.age = age;
}
public int hashCode()
{
return age;
}
public boolean equals( Object obj )
{
boolean flag = false;
Emp emp = ( Emp )obj;
if( emp.age == age )
flag = true;
return flag;
}
}
They are saying i would get false for the below query if i not override the hashcode and equals method.
System.out.println("HashSet Size--->>>"+hs.size());
System.out.println("hs.contains( new Emp(25))--->>>"+hs.contains(new Emp(25)));
System.out.println("hs.remove( new Emp(24)--->>>"+hs.remove( new Emp(24));
System.out.println("Now HashSet Size--->>>"+hs.size());
I got confuse how this is related to hashcode and equals just checking the contains(anyobject) and remove(anyobject) in hashset .
Can somebody explain me the above scenario?