3
package test;
import java.util.HashMap;
public class test {
public static void main(String args[]) {
HashMap<ID, String> h = new HashMap<ID, String>();
String b;
ID id1 = new ID(100);
ID id2 = new ID(200);
ID id3 = new ID(200);
h.put(id1, "apple");
h.put(id2, "pear");
**System.out.println(h.containsKey(id3));**
}
}
class ID {
Integer code;
public ID(Integer id) {
this.code = id;
}
@Override
public int hashCode()
{
return code.hashCode();
}
@Override
public boolean equals(Object o)
{
return this.code.equals(o);
}
}
该程序的输出为“false”。我无法理解这个结果。我实现了hashCode和等于哪个被覆盖。我不知道如何解决。如何在java HashMap中使用对象作为键?在Java中使用对象作为键HashMap
@ saka1029他放了另一个'ID'实例具有相同的整数值。所以它应该打印*“真实”*如果他用“等号”方法解决了他的问题。 – Tom