foreach循环遍历List,删除其中某元素报错问题

1. foreach循环遍历List集合,并删除其中的"lisi"

public class TestListDel {

	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		list.add("zhangsan");
		list.add("simon");
		list.add("lisi");
		list.add("smith");
		list.add("lucy");
		
		for (String string : list) {
			if(string.equals("lisi")) {
				list.remove(string);
			}
		}
		
		//list.stream().forEach(name -> System.out.println(name));
		System.out.println(list);

	}

}

报错(java.util.ConcurrentModificationException)如下:

Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
	at java.util.ArrayList$Itr.next(ArrayList.java:859)
	at abc.TestListDel.main(TestListDel.java:32)

2. 错误分析

通过查看源码,发现foreach循环执行时候,底层执行的是Iterator。其代码如下:

/**
     * An optimized version of AbstractList.Itr
     */
    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        Itr() {}

        public boolean hasNext() {
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

当走到 next()方法时候,会执行校验 checkForComodification(),由于modCountexpectedModCount不相等,所以报错了。

而之所以不相等,是由于在执行list.remove(string);时候,modCount的值被修改了。
在这里插入图片描述

3. 总结

foreach循环遍历删除的代码:

for (String string : list) {
	if(string.equals("lisi")) {
		list.remove(string);
	}
}

等价于如下代码:

Iterator<String> it = list.iterator();
while(it.hasNext()){
	if(it.next().equals("simon")) {
		list.remove(it.next());
	}
}

4. 正确的写法,使用迭代器Iterator

public class TestListDel {

	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		list.add("zhangsan");
		list.add("simon");
		list.add("lisi");
		list.add("smith");
		list.add("lucy");
		
		Iterator<String> it = list.iterator();
		while(it.hasNext()){
			if(it.next().equals("simon")) {
				it.remove();
			}
		}
		System.out.println(list);

	}

}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值