Can some one tell me whats wrong with my code. I am not able to figure it out even though following the link Why do I need to override the equals and hashCode methods in Java?
import com.sun.org.apache.xpath.internal.operations.Equals;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Employee a = new Employee(1, "Ram");
Employee b = new Employee(1, "Ram");
Employee c = a;
System.out.println(b.equals(a));
System.out.println(a.hashCode());
System.out.println(b.hashCode());
HashMap<Employee, String> hm = new HashMap<Employee,String>();
hm.put(a, "one");
System.out.println(hm.containsKey(b));
Iterator<Map.Entry<Employee, String>> itr = hm.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry<Employee,String> ent = itr.next();
System.out.println("key "+ent.getKey() +" value " +ent.getValue());
}
}
}
class Employee {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
Employee(int id, String name) {
this.id = id;
this.name = name;
}
public boolean equals(Employee obj)
{
if(this.id==obj.id)
return true;
else
return false;
}
public int hashCode()
{
int result =1;
return (result*37+(name!=null? name.hashCode():0));
}
}
I am overriding equals and hashcode method such that my two employee objects are same. When i search for b object in map,since b's hashCode is same as that of a, next it searches for equality on a and b which is true. Buy why hm.contains(b) returns false in my code, which should be true