Java Tip : How to avoid an java.util.ConcurrentModificationException with ArrayList?

You need to add/delete an item in an ArrayList when you are iterating the list. You will receive the java.util.ConcurrentModificationException exception. For example, the following code will throw an exception after adding an item into list:

public class Sample {

  public static void main(String[] args) {

    List<Integer>  iList = new ArrayList<Integer>();
    for (int i = 0; i != 100; i++)
      iList.add(i);

    int addValue = 1000;
    for (Integer i: iList) {
      if (i%10 == 0) {
        iList.add(addValue++);
      }
    }
}

To avoid java.util.ConcurrentModificationException exception, we can add an item through the iterator of list. If we do the same as the above code, the next access item in list via the iterator will generate the same exception.

public class Sample {

  public static void main(String[] args) {

    List<Integer>  iList = new ArrayList<Integer>();
    for (int i = 0; i != 100; i++)
      iList.add(i);

    int addValue = 1000;

    for (ListIterator<Integer> itr = iList.listIterator(); itr.hasNext();) {
      Integer i = itr.next();
      if (i%10 == 0) {
        itr.add(addValue++);
      }
    }

}

TestNG : Expected Exception Test

It is always good to test the working and output of your unit. But it is more important to test the negative behavior to make application robust. What if you are expecting an exception from a part of code which is not thrown. the point where application has to get terminated, it is moving smoothly to get a dead lock or a pitty crash. Just to save such situation Testing of exception generation is code is very important. There are annotation in TestNG frame work which helps to make is an easy task.

Example

import org.testng.annotations.*;

public class TestNGTest2 {

	@Test(expectedExceptions = ArithmeticException.class)  
	public void divisionWithException() {  
	  int i = 1/0;
	}  

}

In above example, the divisionWithException() method will throw an ArithmeticException Exception, since this is an expected exception, so the unit test will pass.

More advanced example can be observed in the snap shot attached.
Where the scenarios to test says – “Calling this method with null argument throws Exception”.
The test will go green if exception is thrown, else it will go red.

Testing the expected exception

Testing the expected exception