iterator - Improper use of foreach in java? -


i'm trying remove item of type subclass arraylist using foreach, , removing right when finds it.

the code:

for (superclass item : list)    {           if (item instanceof subclass)           {         list.remove(item);           }    } 

i don't know how iterator works in case, i'm asking is: safe? or should throw out of bounds exception?

any appreciated!

you cant remove items list while using foreach statement. concurrentmodificationexception

you need use iterator.remove() method

for(iterator<superclass> = list.iterator(); i.hasnext(); ) {      superclass s = i.next();      if(s instanceof subclass) {         i.remove();      } } 

Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -