Concurrent Modification exception

前端 未结 9 1537
谎友^
谎友^ 2020-11-22 14:36

I have this little piece of code and it gives me the concurrent modification exception. I cannot understand why I keep getting it, even though I do not see any concurrent mo

9条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 14:52

    If the above solutions doesn't work properly. You can use old for-loop for iterating a List at the same time adding new items. See the example below:

    import java.util.*;
    
    public class SomeClass {
        public static void main(String[] args) {
            ArrayList aList = new ArrayList(); // we will iterate this
    
    
            // this will cause ConcurrentModificationException. 
            // Since we are iterating the list, at the same time modifying it.
            /*for(AClass a: aList){
               aList.add(someMethod(a));
            }*/
    
            // old fashion for-loop will help
            int limit = aList.size();
            for(int i=0; ctr

提交回复
热议问题