【问题标题】:Is it not safe to insert into a list while iterating through it? [closed]在迭代列表时插入列表是否不安全? [关闭]
【发布时间】:2013-03-17 02:14:52
【问题描述】:

在遍历列表时插入列表是否不安全?想法?我个人不确定……

【问题讨论】:

  • “列表”并不是那么有用。以这种方式使用某些列表可能是“安全的”,而其他列表可能不是。 “安全”也没有特别明确的定义!
  • 我觉得直接修改列表会抛出concurrentmodification异常
  • 看到这个answer
  • @Affe 没有迭代器是不可能的,对吧?除此之外

标签: java concurrency


【解决方案1】:

正如我所料,它会抛出 ConcurrentModificationException。 我在一个简单的例子上测试它:

public class Test {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        for(Iterator<Integer> it = list.iterator(); it.hasNext();it.next()){
            System.out.println(it.toString());
            list.add(4);
        }
    }
}

将 ArrayList 更改为 LinkedList 给出相同的结果。 如果我记得只有删除操作是有效的

【讨论】:

    【解决方案2】:

    如果您正在使用Iterator 对象迭代集合,那么更改底层集合将创建一个ConcurrentModificationError,这将使代码崩溃。即使您使用的是 for-each 循环,这也适用,因为这种类型的循环隐式声明了 Iterator

    More information on ConcurrentModificationException.

    【讨论】:

      猜你喜欢
      • 2015-01-09
      • 1970-01-01
      • 2012-09-11
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 2021-02-14
      • 2013-10-29
      • 1970-01-01
      相关资源
      最近更新 更多