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.

4

4 回答 4

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.

于 2013-04-26T13:13:42.737 回答
2

Try to remove with your iterator :

i.remove(); // instead of list.remove(c);
于 2013-04-26T13:14:49.857 回答
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

于 2013-04-26T13:20:08.517 回答
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

于 2013-04-26T13:21:35.333 回答