4

When I run this, I get a java.util.ConcurrentModificationException despite me using iterator.remove();

it's obviously me adding the number 6 in the loop. Does this happen because the iterator "doesn't know" it's there and is there anyway to fix it?

public static void main(String args[]){

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

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

    for(Iterator<String> it = list.iterator();it.hasNext();){
        String value = it.next();

        if(value.equals("4")) {
            it.remove();
            list.add("6");
        }

        System.out.println("List Value:"+value);
    }
}

2 Answers 2

15

The ConcurrentModificationException is thrown when calling String value = it.next();. But the actual culprit is list.add("6");. You mustn't modify a Collection while iterating over it directly. You are using it.remove(); which is fine, but not list.add("6");.

While you can solve the problem with Streams, I will first offer a solution with Iterators, as this is a good first step for understanding the problem.

You need a ListIterator<String> if you want to add and remove during iteration:

for (ListIterator<String> it = list.listIterator(); it.hasNext();){
    String value = it.next();

    if (value.equals("4")) {
        it.remove();
        it.add("6");
    }

    System.out.println("List Value: " + value);
}

This should do the trick!


A solution using Streams:

List<String> newList = list.stream()
        .map(s -> s.equals("4") ? "6" : s)
        .collect(Collectors.toList());

Here we create a Stream from your List. We map all values to themselves, only "4" gets mapped to "6" and then we collect it back into a List. But caution, newList is immutable!

Sign up to request clarification or add additional context in comments.

Comments

0

java.util.ConcurrentModificationException is a very common exception when working with java collection classes. Java Collection classes are fail-fast, which means if the Collection will be changed while some thread is traversing over it using iterator, the iterator.next() will throw ConcurrentModificationException. Concurrent modification exception can come in case of multithreaded as well as single threaded java programming environment.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.