对ArrayList操作时报错java.util.ConcurrentModificationException null

  用iterator遍历集合时要注意的地方:不可以对iterator相关的地方做添加或删除操作。否则会报java.util.ConcurrentModificationException

  例如如下代码:

  ArrayList<String> test = new ArrayList<String>();
  test.add("1");
  test.add("11");
  test.add("111");
  test.add("1111");
  test.add("11111");
  int total = test.size();
  for(String temp:test){
  test.remove(temp);
  }

  运行报错如下:

  Exception in thread "main" java.util.ConcurrentModificationException
  at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
  at java.util.AbstractList$Itr.next(AbstractList.java:343)
  at com.jq.busi.work.alarm.AlarmPushBusi.main(AlarmPushBusi.java:369)

  原因分析: 

  参考一个博客的分析:http://blog.sina.com.cn/s/blog_5a15b7d10101brtj.html 

  个人的一个修改方法:

  ArrayList<String> test = new ArrayList<String>();
  test.add("1");
  test.add("11");
  test.add("111");
  test.add("1111");
  test.add("11111");
  int total = test.size();
  for (int count = 0; count < total; count++) {
  String temp = test.get(count);
  test.remove(temp);
  total = test.size();
  count--;
  }

上一篇:HDU 1317(Floyd判断连通性+spfa判断正环)


下一篇:C#编译器怎么检查代码是否会执行