ConcurrentModificationException:.add()与.addAll() [英] ConcurrentModificationException: .add() vs .addAll()
问题描述
List< String>项目=数据;
for(String id:items){
List< String> otherItems = otherData;
// 1. addAll()
//导致ConcurrentModificationException异常
items.addAll(otherItems);
$ b $ // 2.add()
//不会导致异常
for(String otherId:otherItems){
items.add(otherId);
$ b $是因为 add( )
添加到集合Items中,但是 addAll()
创建一个新集合,从而将Items修改为List的另一个实例?
$ b 编辑
项目
和 otherItems
是具体类型 ArrayList< String>
。解决方案操作是正确的,因为它在迭代时修改了集合。
检查实现ArrayList 显示调用 add
或 addAll
应在下一次循环迭代中成功抛出ConcurrentModificationException。事实上,它没有为 add
添加,这意味着在你使用的特定Java版本的ArrayList类中有一个不明确的错误。或者(更可能) otherItems
是空的,所以在第二种情况下,实际上并没有实际调用 add
。
我确定 otherItems
必须为空,因为如果添加到 Items
list以你想要的方式工作,然后它每次都会在循环中增长,导致它无限循环直到死于OutOfMemoryError。
Why does the following occur? Shouldn't both work?
List<String> items = data;
for( String id : items ) {
List<String> otherItems = otherData;
// 1. addAll()
//Causes ConcurrentModificationException
items.addAll(otherItems);
// 2. .add()
//Doesn't cause exceptions
for( String otherId : otherItems ) {
items.add(otherId);
}
}
Is it because add()
adds to the collection Items, but addAll()
creates a new collection thus modifying Items to be a different instance of List?
Edit
items
and otherItems
are of concrete type ArrayList<String>
.
解决方案 Neither operation is proper, since it modifies the collection while iterating it.
Examining the implementation of ArrayList shows that calling either add
or addAll
should successfully throw the ConcurrentModificationException on the next loop iteration. The fact that it isn't doing that for add
means that either there is an obscure bug in the ArrayList class for the particular version of Java you have; or (more likely) otherItems
is empty, so in the second case, you aren't actually calling add
at all.
I'm sure otherItems
must be empty, because if adding to the Items
list "worked" in the way you want, then it would grow every time around the loop, causing it to loop indefinitely until dying with an OutOfMemoryError.
这篇关于ConcurrentModificationException:.add()与.addAll()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!