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

  • 相关阅读:
    python 序列排序 排序后返回相应的索引
    海明距离
    hive学习01词频统计
    自然语言处理之LCS最长公共子子序列
    自然语言处理之关键词提取TF-IDF
    自然语言处理之比较两个句子的相似度 余弦相似度
    linux命令tar压缩解压
    linux学习之软件包安装
    集群间数据迁移报错
    hive学习04-员工部门表综合案例
  • 原文地址:https://www.cnblogs.com/mabaishui/p/1886943.html
Copyright © 2011-2022 走看看