java.util.ConcurrentModificationException异常处理


ConcurrentModificationException异常处理


  ConcurrentModificationException异常是Iterator遍历ArrayList或者HashMap数组时,通过代码修改了数组的大小,而Iterator(Object ele=it.next())会检查数组的size(),当数组的大小变化时,就会产生ConcurrentModificationException异常。 

 for(Integer x : list){
     if(x % 2 == 0)
         list.remove(x);  //此句会修改list的size(),当进入下一次for循环就会抛出异常
 }

  解决办法是通过Iterator修改list。

 Iterator<Integer> itr = list.iterator();
      while(itr.hasNext()){
           if(itr.next() % 2 == 0)   //itr.next()返回迭代器刚越过的元素的引用,返回值是Object,需要强制转换成自己需要的类型
               itr.remove();         //删除迭代器刚越过的元素
 }

 关于Java的Iterator的详细讲解见:http://cmsblogs.com/?p=1185

posted @ 2016-05-28 17:00  best.lei  阅读(213)  评论(0编辑  收藏  举报