How avoid ConcurrentModificationException while iterating collection

How avoid ConcurrentModificationException while iterating collection

Answer : For explanation please refer this. Please have java program to avoid CCM exception:

package com.javahonk.iteratorenumeration;

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

public class AvoidCCMException {

	public static void main(String[] args) {

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

	arrayList.add("Java");
	arrayList.add("Honk");
	arrayList.add("CCMTest");

	//avoid concurrent modification exception
	Iterator<String> iterator = arrayList.iterator();
	while (iterator.hasNext()) {
		String string = (String) iterator.next();
		System.out.println(string);
		if (string.equalsIgnoreCase("Honk")) {
			iterator.remove();
		}
	}

	System.out.println("\nbelow code will throw exception");
	//throw concurrent modification exception
	iterator = arrayList.iterator();
	arrayList.remove(0);
	while (iterator.hasNext()) {
		String string = (String) iterator.next();
		System.out.println(string);

	}

	}

}

 

Output:

How avoid ConcurrentModificationException while iterating collection

Leave a Reply

Your email address will not be published. Required fields are marked *