Java foreach循环中的ConcurrentModificationException

Java foreach循环中的ConcurrentModificationException,java,collections,arraylist,concurrentmodification,Java,Collections,Arraylist,Concurrentmodification,在我的代码中: Collection<String> c = new ArrayList<>(); Iterator<String> it = c.iterator(); c.add("Hello"); System.out.println(it.next()); Collection c=newarraylist(); 迭代器it=c.Iterator(); c、 加上(“你好”); System.out.println(i

在我的代码中:

    Collection<String> c = new ArrayList<>();
    Iterator<String> it = c.iterator();
    c.add("Hello");
    System.out.println(it.next());
Collection c=newarraylist();
迭代器it=c.Iterator();
c、 加上(“你好”);
System.out.println(it.next());
发生异常,因为创建迭代器后我的集合发生了更改

但在这段代码中:

 ArrayList<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(2);
    list.add(3);
    for (Integer integer : list) {     // Exception is here
        if (integer.equals(2)) {
            list.remove(integer);
        }
    }
ArrayList list=new ArrayList();
增加第(1)款;
增加(2);
增加(3);
对于(Integer:list){//异常在这里
if(整数等于(2)){
删除(整数);
}
}
为什么会发生异常


在第二段代码中,我在for each循环之前对集合进行了更改。

您也在for each循环中更改了集合:

  list.remove(integer);

如果需要在迭代时删除元素,可以跟踪需要删除的索引,并在for each循环完成后将其删除,或者使用允许并发修改的集合。

在第二个循环中,原因相同-从列表中删除元素

要在循环时从
列表中删除元素,请使用标准的老式for循环:

for(int i=0;i<list.size();i++) {

for(int i=0;i如果您需要在使用更好的语法进行迭代时删除元素,那么这里有一种最干净的方法,可以永远不获取ConcurrentModificationException:

// utility method somewhere
public static < T > Iterable< T > remainingIn( final Iterator< T > itT ) {
    return new Iterable< T >() {
        @Override
        public Iterator< T > iterator() {
            return itT;
        }
    }
}

// usage example
Iterator< Integer > itI = list.iterator();
for ( Integer integer : remainingIn( itI ) ) {
    if ( integer.equals( 2 ) ) {
        itI.remove();
    }
}
//某个地方的实用方法
公共静态Iterableremainging(最终迭代器itT){
返回新的Iterable(){
@凌驾
公共迭代器迭代器(){
返回itT;
}
}
}
//用法示例
迭代器itI=list.Iterator();
for(整数:remaingin(itI)){
if(整数等于(2)){
itI.remove();
}
}

您可以改为使用,它不是很有效,但可以解决ConcurrentModificationException,并且您可以安全地使用remove方法。

异常是因为您正在迭代并从列表中删除元素

 for (Integer integer : list) {     // Exception is here because you are iterating and also removing the elements of same list here
        if (integer.equals(2)) {
            list.remove(integer);
        }

如果remove()不修改集合,你认为它做什么?for each使用迭代器。这个问题似乎离题了,因为它没有显示以前的研究