How to Deal With java.util.ConcurrentModificationException With ArrayList

It is literally occurred when you needed to modify the list while you are iterating it in the same time.
I have two options for you to consider and use at your own risk.

This is the example that cause an error

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.ArrayList;
import java.util.List;

public class TestAddRemoveList
{

  public static void main( String args[] )
  {
    List< String > list = new ArrayList< String >();
    list.add("A");
    list.add("B");

    for( String str : list )
    {
      if( str.equals( "B" ) )
      {
        list.remove( new String("B" ) );
      }
    }
  }
}

This is the first option you could use CopyOnWriteArrayList but there are some drawbacks too. This is the modified result and it worked for me.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class TestAddRemoveList
{

  public static void main( String args[] )
  {
    List< String > list = new CopyOnWriteArrayList< String >();
    list.add("A");
    list.add("B");

    for( String str : list )
    {
      if( str.equals( "B" ) )
      {
        list.remove( new String("B" ) );
      }
    }
  }
}

This is the other option. You could you iterator to modify the list

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TestAddRemoveList
{

  public static void main( String args[] )
  {
    List< String > list = new ArrayList< String >();
    list.add("A");
    list.add("B");
    list.add("C");

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

    for( String str : list )
    {
      System.out.println( str );
    }
  }
}
Oct 6th, 2009

Comments