-3

Why does the following code throw java.util.ConcurrentModificationException ??

Could someone please explain ConcurrentModificationException in general and in reference to this code! Thanks.

import java.util.ArrayList;
import java.util.List;

public class Test {
public static void main(String args[]){

    List<String> list = new ArrayList<String>();

    list.add("a");
    list.add("b");
    list.add("c");

    for(String s : list){
        if(s.equals("a"));
        list.remove("a");
        }
    System.out.println(list);
    }
}
  • your using an iterator with the enhanced for loop. with an iterator you need to remove the value using the iterator. – Neil Locketz Nov 19 '13 at 01:00

3 Answers3

1

I would keep it simple

import java.util.ArrayList;
import java.util.List;

public class Test {
public static void main(String args[]){

    List<String> list = new ArrayList<String>();

    list.add("a");
    list.add("b");
    list.add("c");

    int i;

    //Go through each element of list
    for (i = 0; i < list.size(); i++)
    {
        //Test if element needs deleting
        if (list.get(i).equals("a")){
            //Delete element
            list.remove(i);
            //Update reference given element deleted
            i--;
        }
    }
    System.out.println(list);
    }
}
0

You cannot modify the contents of a collection while iterating over the collection, as this would invalidate the iteration. Doing so results in a ConcurrentModificationException.

the line

list.remove("a");

is within the iteration and is causing the exception.

EJK
  • 12,332
  • 3
  • 38
  • 55
0

See documentation

as it says:

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

It can be done by using explicitly Iterator

for (Iterator<String> it = list.iterator(); it.hasNext(); ) {
    if (it.next().equals("a")) {
        it.remove();
    }
}

Using simple for-each loop you don't have access to iterator (but it is used to run such a loop), so you cannot do any structural modifications.

Maciej Dobrowolski
  • 11,561
  • 5
  • 45
  • 67