Sealyu

--- 博客已迁移至: http://www.sealyu.com/blog

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  618 随笔 :: 87 文章 :: 225 评论 :: 0 Trackbacks
今日在调试程序时,出现了 java.util.ConcurrentModificationException,出错代码如下:

for(Iterator ite = candidateObjDtoList.iterator(); ite.hasNext(); ) {
       CandidateObjDto dto 
= (CandidateObjDto)ite.next();
       
if(dto.getType() == Constants.CANDIDATE_OBJ_TYPE_SET) {
                dto.setVoteType(Constants.VOTE_TYPE_ABSTAIN);
       }
 else {
               candidateObjDtoList.remove(dto);        
      }

}
      在网上搜索到资料如下:
在Map或者Collection的时候,不要用它们的API直接修改集合的内容,如果要修改可以用Iterator的remove()方法,例如:
    
public void setReparation( Reparation reparation ) {
        
for (Iterator it = this.reparations.iterator();it.hasNext();){    //reparations为Collection
            Reparation repa = (Reparation)it.next();
            
if (repa.getId() == reparation.getId()){
                
this.reparations.remove(repa);
                
this.reparations.add(reparation);
            }

        }

   }


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

    
public void setReparation( Reparation reparation ) {
        
boolean flag = false;
        
for (Iterator it = this.reparations.iterator();it.hasNext();){    //reparations为Collection
            Reparation repa = (Reparation)it.next();
            
if (repa.getId() == reparation.getId()){
                it.remove();
                flag 
= true;
                
break;
            }

        }

        
if(flag){
          
this.reparations.add(reparation);
        }

    }

     成功解决了所遇问题,成功后的代码如下:
 
for(Iterator ite = candidateObjDtoList.iterator(); ite.hasNext(); ) {
        CandidateObjDto dto 
= (CandidateObjDto)ite.next();
        
if(dto.getType() == Constants.CANDIDATE_OBJ_TYPE_SET) {
                dto.setVoteType(Constants.VOTE_TYPE_ABSTAIN);
//对该候选项投弃权票
        }
 else {
                 ite.remove();
        }

}
   
posted on 2008-11-03 16:07 seal 阅读(241) 评论(0)  编辑  收藏 所属分类: Java基础

只有注册用户登录后才能发表评论。


网站导航: