private List<String> duplicateParamList(Map<DistName, List<String>> totalHashMap, Map.Entry<String, String> param,
Map.Entry<DistName, ManagedObject> entry) {
List<String> duplicateList = new ArrayList<>();
if (totalHashMap.isEmpty()) {
List<String> values = new ArrayList<>();
values.add(param.getValue());
totalHashMap.put(entry.getKey(), values);
return duplicateList;
}
for (Map.Entry<DistName, List<String>> totalEntry : totalHashMap.entrySet()) {
if (totalEntry.getValue().contains(param.getValue())) {
duplicateList.add(param.getKey());
} else {
if (totalHashMap.containsKey(entry.getKey())) {
totalHashMap.get(entry.getKey()).add(param.getValue());
} else {
List<String> valueList = new ArrayList<>();
valueList.add(param.getValue());
totalHashMap.put(entry.getKey(), valueList);
}
}
}
return duplicateList;
}
它将抛出此异常: java.lang.reflect.InvocationTargetException --- java.util.ConcurrentModificationException
如何解决这个问题?非常感谢。
这是我使用Iterator替换for,但它也没有效果:
Iterator<Map.Entry<DistName, List<String>>> iterator = totalHashMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<DistName, List<String>> totalEntry = iterator.next();
if (totalEntry.getValue().contains(param.getValue())) {
duplicateList.add(param.getKey());
} else {
if (totalHashMap.containsKey(entry.getKey())) {
totalHashMap.get(entry.getKey()).add(param.getValue());
} else {
List<String> valueList = new ArrayList<>();
valueList.add(param.getValue());
totalHashMap.put(entry.getKey(), valueList);
}
}
}
答案 0 :(得分:0)
摆脱循环内的totalHashMap.put
调用,CME将消失。使用迭代器运行它时,你无法通过结构修改集合来逃避它。并发修改会混淆迭代器,导致异常情况的并发修改会引发ConcurrentModificationException
。