2

I wanted to display the numbers occuring in a character list and then remove that number. Here is my code:

package mytrials;

import java.util.ArrayList;
import java.util.ListIterator;

public class MyTrials {
    public static void main(String[] args) {
    ArrayList<Character> list = new ArrayList<Character>();
    list.add('a');
    list.add('1');
    list.add('5');
    System.out.println(list.size());
    for( ListIterator i = list.listIterator(list.size());  i.hasPrevious();){
        Character c = (Character) i.previous();
        if( Character.isDigit(c)){
            System.out.println(c + " is a digit");
            list.remove(c);
        }
    }
    System.out.println(list.size());
}
}

Here is the error message:

3
5 is a digit
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$ListItr.previous(AbstractList.java:386)
at mytrials.MyTrials.main(MyTrials.java:27)
Java Result: 1

What is the cause of this error and how can it be rectified.

Nivetha
  • 698
  • 5
  • 17
  • 2
    you are using ListIterator , which is not a fail-safe iterator , that is why you are getting a concurrentmodificationexception – Satya Apr 26 '13 at 13:13

4 Answers4

8

Try

i.remove(); 

instead of

list.remove(c);

See here

Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.

Use Iterator instead of the for-each(loop) construct when you need to:

  • Remove the current element. The for-each construct hides the iterator, so you cannot call remove. Therefore, the for-each construct is not usable for filtering.

  • Iterate over multiple collections in parallel.

Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
2

Try to remove with your iterator :

i.remove(); // instead of list.remove(c);
mki
  • 635
  • 3
  • 10
0

The cause of the error is that the iterator's list was modified by using list.remove(c);.When a list is modified directly, the iterator becomes invalid, thus causing your error.

As Achintya Jha posted, you should use the iterator's remove function

Bibz
  • 321
  • 2
  • 11
0

list-iterator is a fail-fast iterator and throws an exception when a thread is trying to modify the list content while another thread is iterating it.

This might help and this one

Community
  • 1
  • 1
dora
  • 1,314
  • 2
  • 22
  • 38