问题描述
我处于一个非常奇特的状态。我有一个如下所示的列表: List< String> list = new ArrayList< String>();
list.add(a);
list.add(b);
现在当我使用多种类型的遍历时,像使用高级for,iterator和normal for循环,下面是示例代码片段:
高级循环:
for(String a:list){
System.out.println(a);
list.add(f);
}
} catch(Exception e){
e.printStackTrace();
$ / code $ / $ p
2 Iterator:/
try {
Iterator< String> itr = list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
list.add(f);
}
} catch(Exception e){
e.printStackTrace();
$ / code $ / pre
$ b 正常循环:
for(int i = 0; i< list.size(); i ++){
System.out.println(list.get(i));
list.add(f);
$ b现在,奇怪的问题是,当使用高级的for-loop和iterator ,我得到以下异常:
java.util.ConcurrentModificationException $ b $在java.util.ArrayList $ Itr。 checkForComodification(Unknown Source)
在java.util.ArrayList $ Itr.next(未知源)
我知道的原因是,当遍历列表时,不能修改它并行。
但是当我使用正常的循环,那么它正常工作,我是否缺少的东西??
请帮助!!! ..
解决方案列表,它使从它创建的任何Iterator对象失效。高级循环(1)编译成与迭代器循环(2)几乎相同的代码,这意味着在后台创建了一个Iterator对象。
javadocs for 有更多详细信息。
如果您想在迭代时添加,请使用
ListIterator listIter =。 ..
while(listIter.hasNext())
{
if(shouldAdd(iter.next())){$ b $ iter.add(....)
I am in a very peculiar state. I have a list something like below :-
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
Now when i do multiple type of traversing, like using advanced for, iterator, and normal for loop, below are the sample code snippets :-
1> Advanced Loop :-
try {
for(String a : list) {
System.out.println(a);
list.add("f");
}
} catch (Exception e) {
e.printStackTrace();
}
2> Iterator :-
try {
Iterator<String> itr = list.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
list.add("f");
}
} catch (Exception e) {
e.printStackTrace();
}
3> Normal Loop :-
for (int i=0;i<list.size();i++) {
System.out.println(list.get(i));
list.add("f");
}
Now, the peculiar problem is, that when using advanced for-loop and iterator, i get the following exception : -
java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
the reason i know, that while iterating through a list, one cannot modify it parallely.
but when i use the normal for loop, then it works properly, Am i missing something??
Please Help!!!..
解决方案 If you modify a List, it invalidates any Iterator objects created from it. The advanced loop (1) compiles to nearly the same code as the iterator loop (2), meaning that there is an Iterator object created behind the scenes.
The javadocs for ConcurrentMOdificationException have more details.
If you want to add while iterating, use
ListIterator listIter = ...
while(listIter.hasNext())
{
if(shouldAdd(iter.next())) {
iter.add(....)
}
}
这篇关于遍历列表时获取ConcurrentException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!