首页 > 解决方案 > “等于”的错误覆盖?

问题描述

卡在测试象牙上:

 class MyKeys {
 Integer key;
 MyKeys(Integer k) {
 key = k;
 }
 public boolean equals(Object o) {
 return ((MyKeys) o).key == this.key;
 }
}

这个代码片段:

Map m = new HashMap();
MyKeys m1 = new MyKeys(1);
MyKeys m2 = new MyKeys(2);
MyKeys m3 = new MyKeys(1);
MyKeys m4 = new MyKeys(new Integer(2));
m.put(m1, "car");
m.put(m2, "boat");
m.put(m3, "plane");
m.put(m4, "bus");
System.out.print(m.size()); 

所以,我的预期输出是“2”,而实际上是 4。我想覆盖 equals 方法的正确性存在一些问题。任何帮助都是有用的。

标签: javaequals

解决方案


您必须使用“.equals()”而不是“==”来比较对象的键。您还需要根据需要实现 hashCode()。


推荐阅读