-1
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;
  }

it will throw this exception: java.lang.reflect.InvocationTargetException ---java.util.ConcurrentModificationException

how to solve this problem? thanks a lot.

this is I use Iterator to replace the for, but it is also not effective:

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);
    }
  }
}
danny
  • 113
  • 1
  • 3
  • 9

1 Answers1

0

Get rid of the totalHashMap.put call inside the loop and the CME will go away. You can't get away with structurally modifying the collection concurrently with running over it with an iterator. That concurrent modification messes up the iterator, and concurrent modification leading to an exceptional situation raises a ConcurrentModificationException.

Lew Bloch
  • 3,364
  • 1
  • 16
  • 10