Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

how
resolve
error
concurrent
modification

How to resolve the "java.util.concurrentmodificationexception"

Educative Answers Team

The java.util.concurrentmodificationexception is an error in Java. The error occurs when the iterator is traversing a list, and a command is used to change an element’s value during that traversal.

Code

The following example gives an error because the list is printed using an iterator,​ and the value “3” is being removed. These instructions can not be executed in this order. Therefore, ​they must be executed separately.

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

class ConcurrentModificationExceptionExample {

	public static void main(String args[]) {
		List<String> myList = new ArrayList<String>();

		myList.add("1");
		myList.add("2");
		myList.add("3");
		myList.add("4");
		myList.add("5");

		Iterator<String> it = myList.iterator();
		while (it.hasNext()) {
			String value = it.next();
			System.out.println("List Value:" + value);
			if (value.equals("3"))
				myList.remove(value); //this line gives
								   // error
		}
	}
}

When the following line is commented, the code runs perfectly.

if (value.equals("3"))
    myList.remove(value);

However, what if the user needs to remove the value equal to three from the list? Then, printing and removal will be done separately.

svg viewer

Code

The following code correctly removes the value equal to 3 and prints the list.

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

class ConcurrentModificationExceptionExample {

	public static void main(String args[]) {
		List<String> myList = new ArrayList<String>();

		myList.add("1");
		myList.add("2");
		myList.add("3");
		myList.add("4");
		myList.add("5");

		myList.remove("3"); //This removes the element

		Iterator<String> it = myList.iterator();
		while (it.hasNext()) {
			String value = it.next();
			System.out.println("List Value:" + value);
		}
	}
}

RELATED TAGS

how
resolve
error
concurrent
modification
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring