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

  • 相关阅读:
    代码编译时JDK版本和运行时JDK版本不一致启动项目报错
    Apache 环境变量配置
    Android NDK 环境变量配置
    Android SDK 环境变量配置
    JAVA 环境变量配置
    FFmpeg Download
    JAVA SE Download
    VS 2015 Download
    BASS HOME
    C++11的闭包(lambda、function、bind)
  • 原文地址:https://www.cnblogs.com/mabaishui/p/1886943.html
Copyright © 2011-2022 走看看