不要在ArrayList的foreach中进行remove操作

运行下面的代码会抛出异常

package com.csea;


import java.util.ArrayList;
import java.util.List;

/**
 * @author Csea
 * @title
 * @date 2020/4/26 15:55
 */
public class Listadd {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("c");
        list.add("s");
        list.add("e");
        list.add("a");
        for (String temp : list) {
            if ("c".equals(temp)) {
                list.remove(temp);
            }
        }
        System.out.println(list);
    }
}
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 com.csea.Listadd.main(Listadd.java:19)

可以看一下他的实现

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();
        }
    }

根据代码,集合在进行遍历的时候维护了一个为0的游标,会把整个集合扫描一次,当cursor==size的时候就退出遍历。当我们的代码执行了remove()方法之后,所有的值都会往前拷贝,也就是size=size-1,这个时候cursor的值也是刚好等于了这个值,当执行到hasnext()的时候,返回了false,退出循环。没有执行next方法中的checkForComodification(),也就没法判断expectedModCount 和 modCount 的值是否相等,也就抛出了异常。
抛出这个异常是触发了Java中的fail-fast机制,这是集合中常见的错误检测机制。

解决方法,将list转为Iterator 来进行remove()操作

			List<String> list = new ArrayList<>();
            list.add("c");
            list.add("s");
            list.add("e");
            list.add("a");

            Iterator iterator = list.iterator();
            while (iterator.hasNext()) {
                if (iterator.next().equals("c")) {
                    iterator.remove();
                }
            }
            System.out.println(list);

在多线程的情况下:
1.对遍历进行枷锁
2.使用CopyOnWriteArrayList 代替ArrayList,容器内部会对Iterator遍历进行枷锁。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值