【发布时间】:2011-07-22 17:13:47
【问题描述】:
我的代码如下所示:
private void MethodToDo(SpecialObject o) {
Map<InfoObj, Integer> totalNeeds = new HashMap<InfoObj, Integer>();
for (ListObject obj : o.getListOfObjects()) {
InfoObj infoObj = new InfoObj(obj.getTitle(), obj.getId());
Integer need = totalNeeds.get(infoObj);
if (need == null) {
need = new Integer(obj.getNeeded());
} else {
need = need + obj.getNeeded();
}
totalNeeds.put(infoObj, need);
}
}
该对象是一个私有内部类(与该方法在同一类中),如下所示:
private class InfoObj {
private String title;
private Integer id;
public InfoObj(String title, Integer id) {
this.title = title;
this.id = id;
}
public String getTitle() {
return title;
}
public Integer getId() {
return id;
}
@Override
public boolean equals(Object io2) {
if (this == io2) { return true; }
if ( !(io2 instanceof InfoObj) ) { return false; }
InfoObj temp = (InfoObj) io2;
return this.id.equals(temp.id) && this.title.equals(temp.title);
}
@Override
public int hashCode() {
final int prime = 7;
int result = 1;
result = prime * result
+ ((this.title == null) ? 0 : this.title.hashCode());
result = prime * result
+ ((this.id == null) ? 0 : this.id.hashCode());
return result;
}
然而,尽管重写了 equals 和 hashCode 方法,hashMap 仍将包含重复键(如在 title 和 id 中是等价的......但仍会出现在多个位置)。我认为我做的一切都是正确的,但意识到我可能会遗漏一些东西......
另外,我知道有重复键,因为我循环遍历 keySet 并输出结果,这导致具有相同标题和 id 的对象多次出现。
【问题讨论】:
-
repeat results是指重复键还是重复值?
-
您是否有显示重复键的 SSCCE?你确定有重复吗?
-
不要相信这与 InfoObj 的内在有关。你的 hashCode() 被调用了吗?
-
表示重复键。我得到了重复键的显示。
-
所以
java.util.HashMap.keySet()多次返回给定键?假设密钥由InfoObj的id和title属性的实例标识。