Reputation: 91
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();
Upvotes: 0
Views: 836
Reputation: 121702
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.
Upvotes: 0
Reputation: 887275
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.
Upvotes: 2