这周在开发中遇到了一个以前没遇到的小Bug,在这里记录下来。
List集合,我们平时都经常使用。但是,我在遍历List集合时,调用了List集合的remove方法来删除集合中的元素,简单的代码结构是这样:
for(String x:list){ if(x.equals("del")) list.remove(x);}但是,就是类似这样一个简单的小程序,在执行时,遇到了如下的异常信息:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
当时很不理解。后来上网找资料,看牛人分析List的源码才发现原因,是因为调用List的remove方法后,使expectedModCount(表示对
ArrayList修改次数的期望值,它的初始值为modCount)和modCount(是AbstractList类中的一个成员变量)导致的.具体解析,可以
参考博客:http://www.cnblogs.com/dolphin0520/p/3933551.html。一步步的分析的很细致。同样,在博客中也给出了解决方案:那就是
使用Iterator提供的remove方法,用于删除当前元素:
public class Test {
public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(2); Iterator<Integer> iterator = list.iterator(); while(iterator.hasNext()){ Integer integer = iterator.next(); if(integer==2) iterator.remove(); //注意这个地方 } }}