I have the below Java code, I have overridden equal,but not hashCode.
My requirement is to check whether the two objects of class HashCodeSampleMain are having same values are not.
I am able to do it without overriding hashCode.
public class HashCodeSampleMain {
public static void main(String[] args) {
HashCodeSample obj1 = new HashCodeSample(100, "surender");
HashCodeSample obj2 = new HashCodeSample(100, "surender");
if (obj1.equals(obj2))
{
System.out.println("both objects are same");
}
}
}
public class HashCodeSample {
int id =0;
String name=null;
public HashCodeSample(int temp_id, String temp_name)
{
id =temp_id;
name =temp_name;
}
@Override
public boolean equals(Object obj) {
HashCodeSample m =(HashCodeSample)obj;
if(this.id ==m.id && this.name ==m.name)
{
return true;
}
else
{
return false;
}
}
}
Output
both objects are same
I want to understand what is importance of hashCode in connection with equal method.