开发者

Element removing while collection iterating

开发者 https://www.devze.com 2023-01-31 09:06 出处:网络
I\'m wondering what is really going on behind the scene when I\'m executing the following peace of code:

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 excepti开发者_如何学Goon.

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


There is usually a better way to do this rather than use iterator.remove(). e.g. in your case, the loop is the same as

if(list.size()> 5) list.remove(5);

If you do need to use iterator.remove() you can still use a for loop.

for(Iterator iterator = list.iterator(); iterator.hasNext();) {
    final Object o = iterator.next();

    if (++count == 5)
       iterator.remove();

    o.toString();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消