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 own remove or add methods, iterator throw concurrentmodificationexception.

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

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -