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 閱讀(261) 評論(0)  編輯  收藏 所屬分類: Java基礎
          主站蜘蛛池模板: 兴和县| 青阳县| 威信县| 浪卡子县| 永年县| 洪湖市| 施秉县| 铜鼓县| 周至县| 万山特区| 太谷县| 肥城市| 游戏| 邵阳市| 鄂托克前旗| 沁源县| 梅河口市| 瑞金市| 湘阴县| 和林格尔县| 库伦旗| 滦南县| 大连市| 油尖旺区| 双江| 荔波县| 临沭县| 乌兰浩特市| 镇坪县| 黎川县| 峨眉山市| 通州市| 昌宁县| 五河县| 博罗县| 静乐县| 奉新县| 韶山市| 海原县| 呼和浩特市| 泌阳县|