参见英文答案 >
Can anyone explain me over ConcurrentModificationException?1个
我有2个HashMap< Integer,Point3D>对象名称是positiveCoOrdinate和negativeCoOrdinates.
我有2个HashMap< Integer,Point3D>对象名称是positiveCoOrdinate和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);如果condition.it工作正常.
如果我在If条件中添加2行(我上面提到的那些),它会抛出错误.
我怎样才能解决这个问题.
谢谢.
解决方法
最简单的方法是制作keySet的副本:
Set<Integer> set= new HashSet<Integer>(positiveCoOrdinates.keySet());
出现此问题的原因是,当您使用遍历键的迭代器时,您正在修改positiveCoOrdinates.
您还可以重构代码并在条目集上使用迭代器.这将是一种更好的方法.
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(); } }