如何修复线程“main”中的异常java.util.ConcurrentModification
发布时间:2020-12-15 02:49:18 所属栏目:Java 来源:网络整理
导读:参见英文答案 Can anyone explain me over ConcurrentModificationException?1个 我有2个HashMap Integer,Point3D对象名称是positiveCoOrdinate和negativeCoOrdinates. 我正在检查PositiveCoOrdinates具有以下条件.如果它满足相应的点添加到negativeCoOrdina
参见英文答案 >
Can anyone explain me over ConcurrentModificationException?1个
我有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(); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |