我有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);
}
}
Run Code Online (Sandbox Code Playgroud)
添加,删除时间我收到以下错误.
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)
Run Code Online (Sandbox Code Playgroud)
对于我的测试,我System.out.println(coOrdinate.x);在If条件内提到了声明.工作正常.
如果我在If条件中添加2行(我上面提到的内容),则会抛出错误.
我怎样才能解决这个问题.
谢谢.
Ren*_*ink 11
最简单的方法是制作keySet的副本:
Set<Integer> set= new HashSet<Integer>(positiveCoOrdinates.keySet());
Run Code Online (Sandbox Code Playgroud)
出现此问题的原因是您正在修改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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4055 次 |
| 最近记录: |