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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With