Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested iterating through list followed by an eventual deletion

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?

like image 969
Zar Avatar asked Feb 20 '23 01:02

Zar


2 Answers

Obviously modifying list when you iterate over it causing the execption. You can use another list to maintain the list of elements to be removed and remove them at the end.

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

for(int i : list) { // ConcurrentModificationException
   Iterator iterator = list.iterator();
   while(iterator.hasNext()) {    
      int n = iterator.next();
      if(n % i == 0) {
          del.add(n);      
      }
   }
}

list.removeALL(del);
like image 122
P.P Avatar answered May 11 '23 13:05

P.P


Make the outer iteration iterate over a copy of the list.

for (int i : new ArrayList<>(list)) {

  Iterator<Integer> iterator = list.iterator();

  while (iterator.hasNext()) {

    int n = iterator.next();

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

  }

}
like image 25
OldCurmudgeon Avatar answered May 11 '23 12:05

OldCurmudgeon