【问题标题】:how to fix the exception java.util.ConcurrentModificationException [duplicate]如何修复异常 java.util.ConcurrentModificationException [重复]
【发布时间】:2017-04-25 09:22:03
【问题描述】:
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);
    }
  }
}

【问题讨论】:

  • 不重复,因为我的迭代器是totalHashMap,使用Iterator也无效。
  • 我用迭代器更新代码

标签: java


【解决方案1】:

摆脱循环内的totalHashMap.put 调用,CME 将消失。您无法在结构上修改集合的同时使用迭代器运行它。并发修改会弄乱迭代器,导致异常情况的并发修改会引发ConcurrentModificationException

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-08
    • 2016-11-17
    • 2016-10-20
    • 2012-07-09
    • 2017-01-15
    • 2019-03-07
    • 2014-05-18
    • 2016-11-12
    相关资源
    最近更新 更多