arraylist - java.util.ConcurrentModificationException with nested loop remove call -
trying code run receiving java.util.concurrentmodificationexception
error when running. think because using nested loops on same arraylist , deleting index of both "concurrently". how avoid problem? in advance .
for(iterator<missile> iteratori = missiles.iterator(); iteratori.hasnext();) { missile missile = iteratori.next(); if(missile.type == 2) { for(iterator<missile> iteratorj = missiles.iterator(); iteratorj.hasnext();) { missile missilej = iteratorj.next(); if(missilej.equals(missile)){ continue; } double cal1 = missilej.xpos - missile.xpos; double cal2 = missilej.ypos - missile.ypos; double radius = math.sqrt(cal1*cal1 + cal2*cal2); if(radius < missile.blastradius) { //collision detection throwing array out of bounds errors missile.detonate(); missilej.detonate(); iteratori.remove(); iteratorj.remove(); } } } }
from javadoc of arraylist:
the iterators returned class's
iterator
,listiterator
methods fail-fast: if list structurally modified @ time after iterator created, in way except through iterator's ownremove
oradd
methods, iterator throwconcurrentmodificationexception
.
since 2 iterators (iteratori
, iteratorj
) iterating same list, iteratori.remove()
cause iteratorj.remove()
throw error.
since missiles
arraylist
, can iterate using indexes (int i
, int j
) , remove using missiles.remove(i)
, missiles.remove(j)
. of course, you'll have adjust index values remove items in list.
Comments
Post a Comment