tags:

views:

251

answers:

4

I have this little piece of code and it gives me the concurrent modification exception. I cannot understand why I keep getting it, even though I do not see any concurrent modifications being carried out.

import java.util.*;
//package p2;

public class Class1 {
    public Class1() {
    }

    public static void main(String[] args) {
        Class1 class1 = new Class1();
        List <String> s = new ArrayList <String> ();
        ListIterator<String> it = s.listIterator();

        for(String a:args)
        s.add(a);

        if(it.hasNext()) {  
            String item = it.next();   
               }  

        System.out.println(s);


    }
}
A: 

You are not allowed to continue iterating over an iterator after the underlying list is modified. Here you create the iterator before adding a few items to s, and then proceed to do a hasNext() and a next() on it after the additions, leading to the ConcurrentModificationException

Yuliy
+1  A: 

From the JavaDoc: for ConcurrentModificatoinException: "it is not generally permssible for one thread to modify a Collection while another thread is iterating over it".

It simply means that if you still have an open iterator, you aren't allowed to modify the list because the iterator loop will break. Try moving ListIterator<String> it = s.listIterator(); till after the for loop.

leonm
+1  A: 

Simple. Between creating the iterator are using the iterator, you added arguments to the list that is being iterated. This is a concurrent modification. Create the iterator AFTER you've finished adding to the list.

Stephen C
+6  A: 

To avoid the ConcurrentModificationException, you should write your code like this:

import java.util.*;
//package p2;

public class Class1 {
    public Class1() {
    }

    public static void main(String[] args) {
        Class1 class1 = new Class1();
        List <String> s = new ArrayList <String> ();

        for(String a:args)
        s.add(a);

        ListIterator<String> it = s.listIterator();    
        if(it.hasNext()) {  
            String item = it.next();   
        }  

        System.out.println(s);

    }
}

A java.util.ListIterator allows you to modify a list during iteration, but not between creating it and using it.

Pascal Thivent