I'm wondering what is really going on behind the scene when I'm executing the following peace of code:
List<Object> list = new ArrayList<Object>();
fillTheList(); // Filling a list with 10 objects
int count = 0;
for (Object o : list) {
count++;
if (count == 5) {
list.remove(count);
}
o.toString();
}
Once element is removed I'm getting ConcurrentModificationException
exception.
I don't understand why after one of elements removing it is impossible just to take the next one available in the collection and proceed with a cycle.
get an Iterator
instead of using the iterator in a for
loop:
int count = 0;
for(final Iterator iterator = list.iterator(); iterator.hasNext();) {
final Object o = iterator.next();
if (++count == 5) {
iterator.remove();
}
o.toString();
}
edit: the reason why you get ConcurrentModificationException
is because the for
loop is using a different Iterator
which was created before your modification will being made with list.remove()
and that Iterator
has a state inside.
Basically you're not allowed to refer to the collection (list
in this case) inside the foreach loop.
Try this instead:
List<Object> list = new ArrayList<Object>();
fillTheList(); // Filling a list with 10 objects
int count = 0;
ListIterator<Object> it = list.listIterator();
while (it.hasNext()) {
Object o = it.next();
count++;
if (count == 5) {
it.remove();
}
o.toString();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With