Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element removing while collection iterating

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.

like image 250
Eugene Avatar asked Feb 25 '23 13:02

Eugene


2 Answers

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.

like image 189
KARASZI István Avatar answered Mar 07 '23 14:03

KARASZI István


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();
}
like image 22
Mikel Avatar answered Mar 07 '23 15:03

Mikel