0

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();

2 Answers 2

2

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.

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

Comments

0

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.

1 Comment

What you write is correct, but what bearing does it have on the question? I don't see how this explains the ConcurrentModificationException, especially as the enhanced for loop iterates over a different collection than the explicitly created iterator.

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.