JAVA foreach中不能使用add/remove
java几种常用的遍历List的方式,for,foreach(增强for循环),iterator。其中在使用foreach和iterator循环时不能使用list的add/remove方法,会导致ConcurrentModificationException。
iterator迭代器
AbstractList
类中维护了modCount
(集合修改次数),而AbstractList
中有一个内部类Itr
(实现了Iterator
接口)维护了一个expectedModCount
(期望集合修改次数),在调用List的iterator
方法时会先对expectedModCount
赋值expectedModCount=modCount
;而使用list的add/remove都会使List中的modCount
+ 1,却不会使expectedModCount
+ 1,从根本上导致了modCount != expectedModCount,引起报错ConcurrentModificationException
(即快速失败(fail-fast))
源码截图:
transient
关键字表示该字段不进行序列化
foreach循环
foreach循环的本质仍然是使用iterator实现的,所以会引起和iterator一样的问题。
解决方案
使用iterator类提供的add/remove方法,并且在高并发场景中应对iterator加锁。