Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
704 views
in Technique[技术] by (71.8m points)

arraylist - java.util.ConcurrentModificationException thrown when adding to List

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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...