Collections 迭代时向ArrayList添加元素时出现异常

Collections 迭代时向ArrayList添加元素时出现异常,collections,Collections,我试图在迭代时将字符串对象添加到ArrayList中。然后我有一个例外,比如: Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859) at java.util.ArrayList$Itr.next(ArrayList.java:831) at com.

我试图在迭代时将字符串对象添加到
ArrayList
中。然后我有一个例外,比如:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
    at java.util.ArrayList$Itr.next(ArrayList.java:831)
    at com.alonegk.corejava.collections.list.ArrayListDemo.main(ArrayListDemo.java:19)
这段代码是-

public static void main(String[] args) {
    ArrayList<String> al =new ArrayList<String>();

    al.add("str1");
    al.add("str2");

    Iterator<String> it = al.iterator();

    while(it.hasNext()){
        System.out.println(it.next());
        al.add("gkgk");

    }
publicstaticvoidmain(字符串[]args){
ArrayList al=新的ArrayList();
新增(“str1”);
新增(“str2”);
迭代器it=al.Iterator();
while(it.hasNext()){
System.out.println(it.next());
al.添加(“gkgk”);
}
此处没有同步。我需要知道此异常的原因?

请参阅
ConcurrentModificationException
。如果要在迭代器中添加新值,请尝试使用
ListIterator

public static void main(String[] args) {
ArrayList<String> al =new ArrayList<String>();

al.add("str1");
al.add("str2");

ListIterator<String> it = al.listIterator();

while(it.hasNext()){
    System.out.println(it.next());
    it.add("gkgk");
 }
}
publicstaticvoidmain(字符串[]args){
ArrayList al=新的ArrayList();
新增(“str1”);
新增(“str2”);
ListIterator it=al.ListIterator();
while(it.hasNext()){
System.out.println(it.next());
添加(“gkgk”);
}
}
请参阅
ConcurrentModificationException
。如果要在迭代器中添加新值,请尝试使用
列表迭代器

public static void main(String[] args) {
ArrayList<String> al =new ArrayList<String>();

al.add("str1");
al.add("str2");

ListIterator<String> it = al.listIterator();

while(it.hasNext()){
    System.out.println(it.next());
    it.add("gkgk");
 }
}
publicstaticvoidmain(字符串[]args){
ArrayList al=新的ArrayList();
新增(“str1”);
新增(“str2”);
ListIterator it=al.ListIterator();
while(it.hasNext()){
System.out.println(it.next());
添加(“gkgk”);
}
}

当我们同时迭代和修改某些内容时,ConcurrentModificationException用于快速失败

我们可以直接使用迭代器进行修改

 for (Iterator<Integer> iterator = integers.iterator(); iterator.hasNext();) {
    Integer integer = iterator.next();
    if(integer == 2) {
        iterator.remove();
    }
}
for(Iterator Iterator=integers.Iterator();Iterator.hasNext();){
整数=迭代器.next();
如果(整数==2){
iterator.remove();
}
}

当我们同时迭代和修改某些内容时,ConcurrentModificationException用于快速失败

我们可以直接使用迭代器进行修改

 for (Iterator<Integer> iterator = integers.iterator(); iterator.hasNext();) {
    Integer integer = iterator.next();
    if(integer == 2) {
        iterator.remove();
    }
}
for(Iterator Iterator=integers.Iterator();Iterator.hasNext();){
整数=迭代器.next();
如果(整数==2){
iterator.remove();
}
}