This question already has an answer here:
Can anyone explain me over ConcurrentModificationException?

(1个答案)


7年前关闭。




我有2个HashMap<Integer,Point3D>对象名称是positiveCoOrdinate and negativeCoOrdinates

我正在按照以下条件检查PositiveCoOrdinates。如果它满足将相应点添加到negativeCoOrdinates中并从positiveCoOrdinates中删除的要求。
  HashMap<Integer, Point3d> positiveCoOrdinates=duelList.get(1);
  HashMap<Integer, Point3d> negativecoOrdinates=duelList.get(2);
  //condition
  Set<Integer> set=positiveCoOrdinates.keySet();
    for (Integer pointIndex : set) {
        Point3d coOrdinate=positiveCoOrdinates.get(pointIndex);
        if (coOrdinate.x>xMaxValue || coOrdinate.y>yMaxValue || coOrdinate.z>zMaxValue) {
            negativecoOrdinates.put(pointIndex, coOrdinate);
            positiveCoOrdinates.remove(pointIndex);
        }
    }

在添加,删除时间时,出现以下错误。
 Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$KeyIterator.next(Unknown Source)
at PlaneCoOrdinates.CoordinatesFiltering.Integration(CoordinatesFiltering.java:167)
at PlaneCoOrdinates.CoordinatesFiltering.main(CoordinatesFiltering.java:179)

对于我的测试,我在System.out.println(coOrdinate.x);条件中提到了If语句。它工作正常。

如果我在If条件内添加2行(我在上面提到的内容),则会引发错误。

我怎样才能解决这个问题。

谢谢。

最佳答案

最简单的方法是制作keySet的副本:

  Set<Integer> set= new HashSet<Integer>(positiveCoOrdinates.keySet());

发生此问题的原因是您在使用迭代键的positiveCoOrdinates时修改了Iterator

您还可以重构代码,并在条目集上使用迭代器。这将是一个更好的方法。
Set<Entry<Integer, Point3d>> entrySet = positiveCoOrdinates.entrySet();

    for (Iterator<Entry<Integer, Point3d>> iterator = entrySet.iterator(); iterator.hasNext();) {
        Entry<Integer, Point3d> entry = iterator.next();
        Point3d coOrdinate = entry.getValue();
        if (coOrdinate.x > xMaxValue || coOrdinate.y > yMaxValue
                || coOrdinate.z > zMaxValue) {
            Integer pointIndex = entry.getKey();
            negativecoOrdinates.put(pointIndex, coOrdinate);
            iterator.remove();
        }
    }

09-27 05:27