【问题标题】:Modifying a list inside iteration在迭代中修改列表
【发布时间】:2010-12-01 11:28:48
【问题描述】:

我们都知道这是非法的,会抛出ConcurrentModificationException

for (Item i : theList) {
 if (i.num == 123)
  foo(i); // foo modifies theList
}

但是这个呢?

for (Item i : theList) {
 if (i.num == 123) {
  foo(i); // foo modifies theList
  break;
 }
}

因为循环在theLists 的迭代器next 被调用之前就被破坏了,所以没有ConcurrentModificationException。但这是否合法?

【问题讨论】:

  • 第一个不是非法的 - foo 不会更改列表,但最多更改列表中一项的属性。 foo(theList) 将有机会对列表进行非法结构更改。
  • 实际上它确实改变了列表,它删除了 i。
  • 这里太复杂太深无法完全粘贴。假设在某个地方它会导致theList.remove(i) 被调用。

标签: java collections iterator concurrentmodification


【解决方案1】:

再想一想,我得出的结论是,必须如此。 “解决方案”是

for (Item i : theList) {
 if (i.num == 123) {
  theI = i;
  break;
 }
}
foo(theI);  // foo modifies theList

但就调用next 的频率而言,这完全一样。

【讨论】:

  • 同样,您不会更改“列表”(theList),而是更改列表中允许的一个元素。
猜你喜欢
  • 2014-09-17
  • 2017-12-05
  • 1970-01-01
  • 2018-10-12
  • 2019-04-04
  • 2020-09-07
  • 1970-01-01
相关资源
最近更新 更多