一、应用背景
在阿里巴巴开发手册中,有这样一条规定:不要在foreach循环里进行add和remove操作(这里指的是List的add和remove操作),否则会抛出ConcurrentModificationException。remove元素请应用iterator。
二、源码
1.咱们晓得foreach是语法糖,他实质还是iterator进行的循环,因而上面的代码和应用foreach循环是一样的。在循环外面咱们应用“谬误”操作,应用List的add办法进行操作,会抛出ConcurrentModificationException
ArrayList<String> arrayList = new ArrayList<>(); arrayList.add("apple"); Iterator<String> iterator = arrayList.iterator(); while(iterator.hasNext()){ String value = iterator.next(); if("apple".equals(value)){ arrayList.add("orange"); } }