私のコードで何が間違っているか教えてもらえますか?私は、リンクWhy do I need to override the equals and hashCode methods in Java?ハッシュマップオーバーライドequalsとhashcode
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));
}
}
次私は対等と私の2つの従業員のオブジェクトが同じであるようにhashCodeメソッドをオーバーライドしていていても、それを把握することはできませんよ。 マップでbオブジェクトを検索すると、bのhashCodeがaのものと同じであるため、次にaとbの等価性が真であるかどうかを検索します。
従業員の「equals」と「hashcode」の実装を確認する必要があります。 –
'Employee'のコードを共有できますか?問題はおそらくそこにあり、あなたが共有したコードにはありません。 – Mureinik
'equals'メソッドのシグネチャは常に' public boolean equals(Object obj) 'です - ' @ Override'をあなたのものに追加してみてください。 – zapl