Tuesday, May 3, 2016

How to avoid concurrent modification exception in java with Array List

There are some possible ways to avoid concurrent modification exception in java. we can see some possibility ways with example code.

Example I 

If you will try to remove an elements from an array list like below you will get concurrent exception. 
Code below.
for (String str : yourArrayList) {
        if (condition) {
            yourArrayList.remove(str);
        }
}

Solution for the above code:

You should use Iterator and its remove() method to do this. You should not use directly remove() method of array list.

Iterator<String> it = yourArrayList.iterator();

while (it.hasNext()) {
    String str = it.next();

    if (condition)
        it.remove();
}

Example II

 
Suppose if you are not interested to use iterator here, you can choose another option. Means, you should use another array list , which needs to add all of your removable objects. Code below.
ArrayList toRemoveElements = new ArrayList();
for (String str : yourArrayList) {
    if (condition) {
        toRemoveElements.add(str);
    }
}
yourArrayList.removeAll(toRemoveElements);


Example III

There is a third option you can use CopyOnWriteArrayList. Code below.
List<String> yourList = new CopyOnWriteArrayList<String>();
    yourList.add("A");
    yourList.add("B");

    for( String str : yourList )
    {
      if( condition )
      {
        yourList.remove( new String("B" ) );
      }
    }

No comments:

Post a Comment