zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    石墨烯
    spring 安装
    orm 对象关系映射
    刷机问题
    环境必备
    spring 例子
    刷系统——黑屏问题
    android 文件下载
    c# 事件处理
    回忆测试广告理论
  • 原文地址:https://www.cnblogs.com/zhanglei93/p/5537862.html
Copyright © 2011-2022 走看看