有人可以告诉我我的代码有什么问题。即使遵循链接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));
}
}
我重写了equals和hashcode方法,这样我的两个员工对象是相同的。 当我在地图中搜索b对象时,由于b的hashCode与a的相同,接下来它在a和b上搜索相等,这是真的。 为什么hm.contains(b)在我的代码中返回false,这应该是真的
答案 0 :(得分:1)
你的equals方法必须覆盖Object.equals(Object obj):
public boolean equals(Employee obj)
应该是
public boolean equals(Object obj)