【发布时间】:2014-05-28 10:46:29
【问题描述】:
我一直在查看 Java 的 Map api,可能是因为当我更新另一个地图 (map2) 时,我的代码中的某个地图 (map1) 也会更新,或者我编写它的方式可能有问题。
void process(Object superObject) {
Map<Date, Object> map1 = superObject.getValuesForMap();
Map<Date, Object> map2 = map1;
updateValueOf(superObject,map2);
}
这就是我更新 map2 值的方式。
updateValueOfMap(Object superObject,Map<Date, Object> map2){
List<Object> objects = getTheObjectsFromASource;
for (Object obj : objects) {
List<Triple<Date, Double, Object>> triples = superObject.getSomeEntriesWithThisAttribute(obj.getCertainAttrib());
for (Triple<D,D,O> t : triples) {
Object cache = map2.get(t.first)
if (cache == null) {
cache = new Object();
cache.setThis(t.second);
cache.setThat(t.third);
} else {
Double value = cache.getThis() + t.second; // add the double value from triple to the current cache Object's value
cache.setThis(value); // and update the Object's value in the map
}
map2.put(t.first, cache);
}
}
}
问题是 superObject.getValuesForMap() 中的某些条目也会更新为与 map2 中的相应条目相同的值,每次迭代 for (Triple..)。为什么呢? 响应将不胜感激。提前致谢!
【问题讨论】: