zoukankan      html  css  js  c++  java
  • 为什么会出现 java.util.ConcurrentModificationException 异常?

    在Map或者Collection的时候,不要用它们的API直接修改集合的内容(否则会出现 java.util.ConcurrentModificationException 异常),如果要修改可以用Iterator的remove()方法,例如:

     1 public void setReparation( Reparation reparation ) {   
     2      for (Iterator it = this.reparations.iterator();it.hasNext();){    //reparations为Collection   
     3          Reparation repa = (Reparation)it.next();   
     4          if (repa.getId() == reparation.getId()){   
     5              this.reparations.remove(repa);   
     6              this.reparations.add(reparation);   
     7          }   
     8      }   
     9 }  
    10 

    如上写会在运行期报ConcurrentModificationException,可以如下修改:

     1 public void setReparation( Reparation reparation ) {   
     2     boolean flag = false;   
     3     for (Iterator it = this.reparations.iterator();it.hasNext();){    //reparations为Collection   
     4         Reparation repa = (Reparation)it.next();   
     5         if (repa.getId() == reparation.getId()){   
     6             it.remove();   
     7             flag = true;   
     8             break;   
     9         }   
    10     }   
    11     if(flag){   
    12       this.reparations.add(reparation);   
    13     }   
    14 }  
    15 

    转自:http://www.javaeye.com/topic/124788

  • 相关阅读:
    Linux防火墙使用配置
    es安装笔记
    git仓库免密码登陆配置
    swgger前后端分离api生成
    关于redis
    学习笔记关于springboot
    idea 安装记录
    随记
    开课吧--Python数据分析--第4节 数据七十二变--互动练习:如果你不需要,就让它消失!
    jupyter使用方法
  • 原文地址:https://www.cnblogs.com/mabaishui/p/1886943.html
Copyright © 2011-2022 走看看