Nested iterating through list followed by an event

2019-05-06 13:11发布

I'm trying to iterate throuh a list while already looping through it (nested loops). Consider the code below:

ArrayList<Integer> list = new ArrayList<Integer>(); // add some values to it

for(int i : list) { // ConcurrentModificationException

   Iterator iterator = list.iterator();

   while(iterator.hasNext()) {

      int n = iterator.next();

      if(n % i == 0) {
         iterator.remove();
      }

   }

}

The example above results in a ConcurrentModificationException. The condition to remove an element is, of course, just an example.

I'm sure I'm just missing something; but how should I construct a loop that achieves the same thing in Java without throwing an exception?

7条回答
狗以群分
2楼-- · 2019-05-06 13:49

I haven't tried, but either use:

List<Integer> list = new ArrayList<Integer>(); 
// add some values to it  
for(Iterator<Integer> iterator1 = list.iterator(); iterator1.hasNext();) { 
    int i = iterator1.next();
    for(Iterator<Integer> iterator2 = list.iterator(); iterator2.hasNext();){
        int n = iterator.next();        
        if(n % i == 0) {          
            iterator2.remove();       
        }     
    }  
} 

or if this still throws the ConcurrentModificationException (I'm not sure what happens if you use 2 iterators backed by the same list), then use:

List<Integer> list = new ArrayList<Integer>(); 
// add some values to it  
for(int i : new ArrayList(list)){ // copy list 
    ...
}
查看更多
登录 后发表回答