posts - 43,comments - 75,trackbacks - 0

          今天在寫(xiě)程序時(shí)遇到了 java.util.ConcurrentModificationException? 異常,
          參考網(wǎng)上程序后,解決了問(wèn)題,至少現(xiàn)在沒(méi)有這個(gè)異常了。
          主要是在刪除iterator元素時(shí)使用了原來(lái)的hashmap名稱(chēng),改成直接使用iterator的remove方法就可以了。
          參考如下:

          來(lái)自:http://java.mblogger.cn/zzjie/posts/16422.aspx

          在Map或者Collection的時(shí)候,不要用它們的API直接修改集合的內(nèi)容,如果要修改可以用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);
          ??????????? }
          ??????? }
          ?? }

          如上寫(xiě)會(huì)在運(yùn)行期報(bào)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

          posted on 2006-06-07 18:11 夢(mèng)源 閱讀(952) 評(píng)論(0)  編輯  收藏

          只有注冊(cè)用戶(hù)登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 金华市| 肇庆市| 溆浦县| 霍邱县| 搜索| 马尔康县| 谷城县| 富裕县| 江口县| 西藏| 乌海市| 望江县| 鄱阳县| 资中县| 惠东县| 光山县| 龙南县| 多伦县| 巴马| 宜城市| 卢湾区| 阿合奇县| 岐山县| 屏山县| 兴国县| 蒲城县| 七台河市| 绥德县| 洞头县| 广安市| 赞皇县| 聊城市| 新闻| 黄浦区| 长岛县| 韶山市| 双峰县| 瓮安县| 灌阳县| 蓝山县| 武城县|