在迭代集合时移除元素

4

当我执行以下代码时,我想知道背后到底发生了什么:

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

当元素被删除后,我会收到ConcurrentModificationException异常。

我不明白为什么在删除一个元素后,就无法取出集合中的下一个可用元素并继续循环。

3个回答

7

使用Iterator代替在for循环中使用迭代器:

int count = 0;

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

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

    o.toString();
}
< p > < em >编辑:你之所以会收到< code >ConcurrentModificationException的错误提示,是因为< code >for循环正在使用一个不同的< code >Iterator,而这个< code >Iterator是在你使用< code >list.remove()进行修改之前创建的,而且该< code >Iterator具有内部状态。

这是一个想法,但我真的想知道为什么在删除一个元素后,就不能从队列中取出下一个对象并继续进行。 - Eugene

1

基本上你不允许在 foreach 循环内部引用集合(在这种情况下是 list)。

请尝试使用以下代码:

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

0
通常情况下,使用iterator.remove()并不是最好的方法。例如,在您的情况下,循环与以下代码相同:
if(list.size()> 5) list.remove(5);

如果你确实需要使用iterator.remove(),你仍然可以使用for循环。

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

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

    o.toString();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接