事情是这样的,因为想再回顾一下基础,就写了一个main函数,里面循环删元素的代码。以下:java
List<String> a = new ArrayList<String>();
a.add("a");
a.add("b");
for (String temp : a)
{
if("a".equals(temp)){
a.remove(temp);
}
}
System.out.println( a.toString()); 函数
那么正常状况下我预期是会报异常 :Exception in thread "main" java.util.ConcurrentModificationExceptionspa
可是,结果确是正常删除了。。并且打印出告终果~~着实吓了我一跳,没有异常。。。而后就修改了代码将删除a换成了b,结果是报了异常了!!!哎,这下就纳闷了,这是为何呢!!!code
而后就看了下remove方法的源码~发现报异常的缘由是每当咱们add的时候modcount就会加1,这个时候,还有一个expectedModCount 默认是将modcount 赋值给他,每当咱们删除了一个元素那么remove 方法会先调用checkForComodification()再调用里面的一个fastremove方法,在这个方法里面会再执行modCount++; rem
在checkForComodification方法中进行的操做是:源码
final
void
checkForComodification() {
if
(modCount != expectedModCount)
throw
new
ConcurrentModificationException();
}
若是modCount不等于expectedModCount,则抛出ConcurrentModificationException异常。
List<String> a = new ArrayList<String>();
a.add("a");
a.add("b");
a.add("c");
a.add("d");
a.add("e");
for (String temp : a)
{
if("d".equals(temp)){
a.remove(temp);
}
System.out.println( temp.toString());
}
System.out.println( a.toString());
}io
这个时候的输出结果为:ast
a
b
c
d
[a, b, c, e]class
看结果是没有再循环e删除完d就结束了~thread
因为当删除完d元素后,后面的元素会自动向前移动,而后把最后的元素置位null,也就是告诉gc能够回收了。那么这个时候整个的size就变成了4,固到此就会认为整个循环结束,因此没有报异常。。。