ArrayList快速失败机制源码及特殊失效场景分析

更多面试资料同步整理在github:TrustInCS
本文同步github

简单的一个ArrayList案例

    public static void main(String[] args) {
   
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        for (String s : list){
   
            if ("1".equals(s)){
   
                list.remove(s);
            }
        }
    }
  • 代码会正常执行吗?
    • 不会,那会导致什么?
    • 数组越界?

直接执行一下:

Connected to the target VM, address: '127.0.0.1:64296', transport: 'socket'
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.demo.demo.DemoApplicationTests.main(DemoApplicationTests.java:369)

介绍一下这个异常:

ConcurrentModificationException 并发修改异常

* This exception may be thrown by methods that have detected concurrent
 * modification of an object when such modification is not permissible.
 * <p>
 * For example, it is not generally permissible for one thread to modify a Collection
 * while another thread is iterating over it.  In general, the results of the
 * iteration are undefined under these circumstances.  Some Iterator
 * implementations (including those of all the general purpose collection implementations
 * provided by the JRE) may choose to throw this exception if this behavior is
 * 
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值