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 追球者 阅读(749) 评论(0)  编辑  收藏 所属分类: Java

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


网站导航: