# Solve a modificationexception

I was given a problem where a Java program crashes 50 % of the time. It included this part

for (Object o : l) {
for (Object o2 : l) {
if (!o.equals(o2) && distance(o, o2) <= 1) {
l.remove(o);
}
}


And the exception was a ConcurrentModificationException. So I rewrote it like this instead, then it doesn't crash, but is it correct?

Iterator<Object> itr = l.iterator();
while (itr.hasNext()){
Object o = itr.next();
for (Object o2 : l) {
if (!o.equals(o2) && distance(o, o2) <= 1) {
itr.remove();
break;
}
}
}

• What is this l thing? What kind of objects are we dealing with? – Simon Forsberg Mar 19 '18 at 16:43
• @SimonForsberg It is an ArrayList of geometric primitives e.g. Iterator<Figure> should be used instead. The code is from an assignment where they intentionally have gone too high up the class hierarchy. IIUC it should not be necessary to go so high as Object and the code could be more specific. – Niklas Mar 20 '18 at 0:53