SeanConnery SeanConnery - 4 years ago 283
Java Question

How do I fix java.util.ConcurrentModificationException?

The purpose of my code is to have the user enter a car name, then search through the array list and find an object that matches what the user entered. Whenever I run the code, I get the java.util.ConcurrentModificationException error. An explanation of what this error means and advice for fixing it is much appreciated :)

public static void arrayList()
{
//Declarations
ArrayList<String> list = new ArrayList<String> ();
ListIterator<String> iterator = list.listIterator();
list.add ("Aston Martin");
list.add ("Ferrari");

Scanner scan = new Scanner(System.in);
String car = new String();
String search = new String();


//Prompts user to enter car name
System.out.println ("Enter car name: ");
car = scan.nextLine();

//Searches array list for car
while (iterator.hasNext())
{
search = iterator.next();
if (search.equalsIgnoreCase (car))
{
System.out.println (search);
}
}
}

Answer Source

The Javadocs for the relevant collections and ConcurrentModificationException are clear:

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

You started an iteration over list but then modified it and came back to the iterator.

Don't open your iterator until right before you're about to use it. Even better, since you don't need access to remove(), just use an enhanced for loop:

for(String item: list) {
    if(item.equalsIgnoreCase (car)) {
        System.out.println(item);
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download