0

I got error when removing one of the element in my list of (list of integers). I use iterator to remove that element

Here is my code:

List<List<Integer>> list = new ArrayList<List<Integer>>();
....
....
Iterator<List<Integer>> myListIterator = list.iterator();
int ct1 = 0;
while (myListIterator.hasNext()) {
    List<Integer> val = myListIterator.next(); // here is the error 
    if(ct1 == val.get(0))
        list.remove(val);
    ct1++;
}

And I got this error message:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
    at java.util.ArrayList$Itr.next(Unknown Source)

Does anyone know what's wrong with my code? Thank you guys!

hallz13
  • 59
  • 7

1 Answers1

2

Because you removed an element while using the iterator. A possible solution is, use a loop with index, and you can safely remove the element. You can also remove using myListIterator.remove();

Eldon Hipolito
  • 704
  • 1
  • 8
  • 24