通常,
ConcurrentModificationException在 检测到 修改时引发s ,而不 引起
。如果修改后从未访问过迭代器,则不会引发异常。
ConcurrentModificationException不幸的是,这一微小的细节使它对于检测数据结构的滥用非常不可靠,因为它们仅在损坏完成后才抛出。
这种情况不会抛出a,
ConcurrentModificationException因为
next()修改后不会在创建的迭代器上调用它。
For-each循环实际上是迭代器,因此您的代码实际上如下所示:
List<String> strings = new ArrayList<>(Arrays.asList("A", "B", "C"));Iterator<String> iter = strings.iterator();while(iter.hasNext()){ String string = iter.next(); if ("B".equals(string)) strings.remove("B");}System.out.println(strings);考虑您的代码在您提供的列表上运行。迭代看起来像:
hasNext()
返回true,进入循环,-> iter移至索引0,字符串=“ A”,未删除hasNext()
返回true,继续循环-> iter移至索引1,删除字符串=“ B”。strings
现在长度为2。hasNext()
返回false(iter当前位于最后一个索引,没有更多的索引可用),退出循环。
因此,
ConcurrentModificationException当调用
next()检测到进行了修改时抛出s时,此方案几乎避免了此类异常。
对于您的其他两个结果,我们确实有例外。对于
"A", "B", "C", "D",删除“
B”之后,我们仍然处于循环中,并
next()检测到
ConcurrentModificationException,而对于
"A","B"我来说,它是某种ArrayIndexOutOfBounds被捕获并重新抛出为
ConcurrentModificationException



