java.util.ConcurrentModificationException

java.util.ConcurrentModificationException
今日在调试程序时,出现了 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();
        }

}
   

你可能感兴趣的:(java.util.ConcurrentModificationException)