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 itr = list.iterator();

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

}

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

声明:DungCry.|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - java.util.ConcurrentModificationException异常处理


以此热爱,以此谋生。
Le vent se lève, il faut tenter de vivre