[这基本上是对Jesper的回答,但细节可能会对您有所帮助]
由于使用
new HashMap(map)可以重新创建地图,因此我怀疑
hashCode()DomainObject 的元素将其添加到地图后已更改。
例如,如果您的DomainObject看起来如下
class DomainObject { public String name; long hashCode() { return name.hashCode(); } boolean equals(Object other) { '}然后
Map<DomainObject, Boolean> m = new HashMap<DomainObject, Boolean>(); DomainObject do = new DomainObject(); do.name = "ABC"; m.put(do, true); // do goes in the map with hashCode of ABC do.name = "DEF"; m.get(do);
上面的最后一条语句将返回
null。因为
do您在地图内的对象位于的范围之内
"ABC".hashCode();
"DEF".hashCode()桶里什么也没有。
映射中的对象的hashCode一旦添加到映射中就不应更改。 确保它的最佳方法是hashCode依赖的字段必须是不可变的。



