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
          主站蜘蛛池模板: 盐亭县| 永清县| 舟曲县| 温泉县| 井冈山市| 大同县| 禹州市| 正阳县| 乐山市| 长宁区| 兰考县| 垦利县| 华安县| 伊川县| 龙川县| 上栗县| 石城县| 辽中县| 刚察县| 鲁甸县| 河池市| 来安县| 澳门| 福鼎市| 灵宝市| 衢州市| 天水市| 三台县| 汪清县| 丹巴县| 城市| 昭平县| 子洲县| 肇州县| 兖州市| 台中县| 辽宁省| 南雄市| 宜章县| 信宜市| 广饶县|