[英]map.containsKey never worked in java
我正在基于每个对象中存在的某些相等属性对给定对象进行汇总。
final Map<JBlockedPerGT, JBlockedPerGT> ret = new HashMap<JBlockedPerGT, JBlockedPerGT>();
while (allRows.hasNext()) {
final JBlockedPerGT blockedPerGT = allRows.next();
JBlockedPerGT updated = null;
if (ret.containsKey(blockedPerGT)) {
JBlockedPerGT current = ret.get(blockedPerGT);
updated = current.add(blockedPerGT);
} else {
updated = blockedPerGT;
}
ret.put(updated, updated);
}
return ret.values().iterator();
它永远不会进入if
条件并没有聚集发生和不同的对象每一个处理。 问题是,我无法正确理解它的工作方式。 我的JBlockedPerGT
实现了hashcode和equals方法。
任何人都可以帮助我为什么在ret.containsKey(blockedPerGT)
情况下我不是真的。
我的哈希码和equals方法是
public int hashCode() {
int result = 1;
result = PRIME * result + ((gt == null) ? 0 : gt.hashCode());
result = PRIME * result
+ ((messageType == null) ? 0 : Type.hashCode());
result = PRIME * result
+ ((country == null) ? 0 : country.hashCode());
result = PRIME * result
+ ((network == null) ? 0 : network.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
JBlockedPerGTImpl other = (JBlockedPerGTImpl) obj;
if (gt == null) {
if (other.gt != null)
return false;
} else if (!gt.equals(other.gt))
return false;
if (messageType != other.messageType)
return false;
if (country == null) {
if (other.country != null)
return false;
} else if (!country.equals(other.country))
return false;
if (network == null) {
if (other.network != null)
return false;
} else if (!network.equals(other.network))
return false;
return true;
}
}
谢谢
您的JBlockedPerGT
类可能不遵守hashCode
/ equals
合同。
重写Object
的hashCode
方法可允许哈希集合推断对象的相等性。
JBlockedPerGT
您正在使用HashMap
将JBlockedPerGT
用作键存储,那么正确覆盖JBlockedPerGT#hashCode()
至关重要(因此, equals
应被覆盖)。
参见API 。
编辑
由于您确实有一些equals
/ hashCode
实现,因此我将在相等性测试中仔细检查您正在比较的字段/ hash和它们的真实相关性(例如,如果从持久性中检索到的任何内容都不填充字段之一,该怎么办?错误还是故意的?)。
我还将使用调试器并分析检索到的JBlockedPerGT
对象的内部。
最有可能在将JBlockedPerGT
对象用作地图中的键之后更改了哈希生成属性或确定相等性的属性。
最好将地图关键对象实现为不可变的。 否则,您将陷入类似这样的情况,即由于其“身份”随后发生更改而无法在地图中找到钥匙。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.