Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fix Exception in thread "main" java.util.ConcurrentModificationException [duplicate]

Tags:

java

I have 2 HashMap<Integer,Point3D> objects names are positiveCoOrdinate and negativeCoOrdinates.

I am checking PositiveCoOrdinates with following condition.if it satisfies that corresponding point adding into negativeCoOrdinates and deleting from 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);
        }
    }

While adding,deleting time I am getting the following error.

 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)

For my testing,I mention System.out.println(coOrdinate.x); statement inside If condition.it's working fine.

If I add 2 lines(What I mention above) inside If condition,it throwing error.

How can I fix this.

Thanks.

like image 353
Hanumath Avatar asked Oct 01 '13 11:10

Hanumath


1 Answers

The easiest way is to make a copy of the keySet:

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

The problem occurs because you are modifing the positiveCoOrdinates while you are using an Iterator that iterates through the keys.

You can also refactor your code and use an iterator over the entry set. This would be a better approach.

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();
        }
    }
like image 147
René Link Avatar answered Nov 15 '22 00:11

René Link