我有以下代码:
Map<String, ObjectType> objectMap = new HashMap<String, ObjectType>();
for (ObjectType obj : objects) {
obj.setSomeProperty("property value");
objectMap.put(obj.getADiffProperty(), obj);
}
似乎在循环迭代期间,某些 obj 属性针对与当前设置的键不同的键进行了更改。上面的代码有问题吗?不知何故,对 obj 的引用被 for 循环回收?
此外,这个循环也位于外循环中。
更新:
我在下面提供完整的方法。我观察上述行为的实际位置是在定义为 Map<String, Map<String, GlossaryTerm>> loadedTerms = new HashMap<String, Map<String, GlossaryTerm>>();
的外部 map 中。在 Singleton 类中定义。
List<Audience> audiences = ContentAccess.getAudienceList();
List<GlossaryTerm> glossaryTerms = ContentAccess.getAllReplacementCIs();
for (Audience audience : audiences) {
Map<String, GlossaryTerm> termMap = new HashMap<String, GlossaryTerm>();
for (GlossaryTerm term : glossaryTerms) {
String definition = term.getProductGlossary().get(audience.getName());
if (definition != null)
term.setDefinition(definition);
termMap.put(term.getPhrase(), term);
}
loadedTerms.put(audience.getChannelId(), termMap);
}
最佳答案
我不认为你认为正在发生的事情正在发生。对于每次迭代,对象引用都是它应该的样子。我认为一定发生了其他事情 - 属性在其他地方发生了变化,或者没有您认为它们最初具有的值。放入一些 println 来追踪到底发生了什么。您所显示的代码不能更改错误的属性。
关于java - 在循环中设置 Hashmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2368462/