简体   繁体   中英

Caused by: java.util.ConcurrentModificationException

I don't understand why this is happening. I was doing a bit of research on other questions and I found out that you can't modify an collection while using a for loop. However, I am using an Iterator, why is it not working?

int counter = 0;
    int otherCounter = 0;
    ArrayList<Character> chars = new ArrayList<Character>();
    Iterator<Character> i = chars.iterator();
    for (char s : e.getMessage().toCharArray()) {
        chars.add(s);
    }
    while (i.hasNext()) {
        char s = i.next();
        if (chars.get(otherCounter + 1) == s) {
            counter++;
        } else {
            counter = 0;
        }
        if (counter >= 2) {
            i.remove();
        }
        otherCounter++;
    }

I am getting an error on this line for some reason: char s = i.next();

You're adding to the collection after creating the iterator.
This throws that exception.

You need to create the iterator after you finish modifying the collection.

This is because an "enhanced for loop" as you are using it creates an Iterator behind the scenes.

In fact, when you write:

for (X x: whatever) {
    // do something with x
}

the "real", generated code goes something like:

Iterator<X> iterator = whatever.iterator();

while (iterator.hasNext()) {
    X x = iterator.next();
    // do something with x
}

And this is true if whatever implements Iterable<X> (which List does; in fact, any Collection does)

In your example, you create a List<Character> , create a first Iterator<Character> over it, and your for loop creates another Iterator<Character> , over the same list.

Note that you created the first before you modified your List ... Hence the result. The first Iterator , which you reuse only afterwards, will detect that in the meanwhile, its underlying list has been modified: boom.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM