exception - ConcurrentModificationException in java ArrayList -
i have following code running on thread:
arraylist<ball> allballs; arraylist<ball> toremove = new arraylist<ball>(); (ball ball:allballs) { //exception thrown here ball.move(); if (shouldremove(ball)) { toremove.add(ball); } } allballs.removeall(toremove); toremove.removeall(toremove);
sometimes throws
java.util.concurrentmodificationexception @ java.util.arraylist$arraylistiterator.next(arraylist.java:576)
but when replace line
for (ball ball:allballs) {
by this
for (int i=0; i<allballs.size();i++) { ball ball = allballs.get(i);
no exception thrown.
why?
only reason getting exception collection getting modified in loop/iteration (i think move method modifying object reflected in list).
to explain why getting exception in foreach not in :
foreach loop uses iterator internally. , collections fail fast (immediately report failure), result of next() method of iterator throw exception if collection getting modified in loop. normal loop not use iterator , reason not getting exception in loop there other side effects of modifying in loop size getting changed or iteration becoming infinite.
Comments
Post a Comment