I'm trying to iterate throuh a list while already looping through it (nested loops). Consider the code below:
ArrayList<Integer> list = new ArrayList<Integer>(); // add some values to it
for(int i : list) { // ConcurrentModificationException
Iterator iterator = list.iterator();
while(iterator.hasNext()) {
int n = iterator.next();
if(n % i == 0) {
iterator.remove();
}
}
}
The example above results in a ConcurrentModificationException. The condition to remove an element is, of course, just an example.
I'm sure I'm just missing something; but how should I construct a loop that achieves the same thing in Java without throwing an exception?
You are getting
ConcurrentModificationException
because, while doingfor
loop you are trying to modify thelist
.I am not sure whether following is elegant solution or not, but something like below may work:
You cannot remove an item from a list that is being iterated. One option is to add the items that you need to another list. Finally you have list with the items you need. Or you can iterate over the clone of your original list.
i do some thing pretty similar to you. hav e alook at this code .
i think you could also change the index after removing element from the arraylist.
Make the outer iteration iterate over a copy of the list.
foreach
java syntax hides an iterator but as hiding it, it is not possible to callremove
method on this one.So I would do:
You can see that the same feature is achieved without the need of a secondary iterator.
You can't iterate through the same list in the same time. To sum up, a
modcount
variable is used to detect unexpected change of itself everytime a list is parallely changed or iterated over. Leading thus to aConcurrentModificationException
. It appears very often with multithreaded environment and developers must be aware of it.Furthermore, prefer use
for
loop insteadwhile
loop to iterate over a collection.Why ?
Because with the
while
way, you let the iterator object still in scope after the loop whereas withfor
, it doesn't. A simple ackward call toit.next()
would end up with aNoSuchElementException
.It is a best practice to keep ;)
Obviously modifying
list
when you iterate over it causing the execption. You can use another list to maintain the list of elements to be removed and remove them at the end.