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

  • 相关阅读:
    实验
    概率与期望
    2020CSP-S模板
    洛谷:P2538 [SCOI2008]城堡
    洛谷P1731 生日蛋糕
    洛谷 P1180 石子合并
    洛谷 P2831 愤怒的小鸟
    浅谈状压DP
    浅谈线段树
    LCA-树链剖分
  • 原文地址:https://www.cnblogs.com/mabaishui/p/1886943.html
Copyright © 2011-2022 走看看