Duffblog

          前進一步,看看,需要前進更大一步才可以。

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            5 隨筆 :: 53 文章 :: 5 評論 :: 0 Trackbacks
          今天,寫程序,關于Iterator遍歷,出現了這個java.util.ConcurrentModificationException。這個問題,已經碰到了好幾次了,再次,在網上查找,終于,找到了一個比較滿意的答案。如下:

          /*********************************************************************************

          在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);
          ??????? }
          ??? }

          具體可以參考:http://gceclub.sun.com.cn/yuanchuang/week-14/iterator.html

          *******************************************************************************/


          深入探討Iterator模式,見下一篇。




          posted on 2006-05-09 19:19 追球者 閱讀(760) 評論(0)  編輯  收藏 所屬分類: Java
          主站蜘蛛池模板: 城步| 鄂温| 波密县| 芜湖县| 石狮市| 桃园县| 黄梅县| 彩票| 海兴县| 大足县| 安龙县| 时尚| 朔州市| 萍乡市| 开封县| 芜湖县| 多伦县| 永登县| 称多县| 区。| 宁南县| 茌平县| 长岭县| 时尚| 桃源县| 盘锦市| 米泉市| 武宁县| 伽师县| 龙游县| 竹北市| 徐汇区| 汶川县| 青岛市| 恭城| 昌黎县| 铁力市| 宁都县| 上蔡县| 屯昌县| 玉溪市|