1,ArrayList 移除元素时,有时候报错,有时候不报错
List<String> a = new ArrayList<>();
a.add("1");
a.add("2");
for (String temp : a) {
if("1".equals(temp)){
a.remove(temp);
}
}
上面代码在编译和运行时都不会报错,并且也能正常remove掉元素,但是如果将"1" 换成"2",运行时就会报ConcurrentModificationException.首选需要分析ArrayList的源码,ArrayList类继承自AbstractList类,该类中有一个成员变量:
protected transient int modCount = 0;
modCount用于记录变更次数,当add或者remove时,都会自增1
foreach时会调用ArrayList的iterator方法,该返回一个Itr类型的内部类,该内部类有几个需要注意的成员变量:
int cursor; // index of next element to return
int expectedModCount = modCount;
cursor用于记录获取到哪个元素,expectedModCount用于记录变更次数,如果在iter过程中删除了一个元素,在调用iter.next()时会调用 Itr.