异常:java.util.ConcurrentModificationException

重现异常: 
import java.util.ArrayList;
import java.util.Iterator;

class User {
    private String userName, password;
    private int ID;

    User(int p_ID, String p_userName, String p_password) {
        ID = p_ID;
        userName = p_userName;
        password = p_password;
    }
}

public class Test {
    static ArrayList al = new ArrayList();

    public static void main(String[] args) {
        add();
        clear();
    }

    public static void add() {
        for (int i = 0; i < 5; i++) {
            al.add(new User(i, "userName", "password"));
        }
    }

    public static void clear() {
        Iterator it = ((ArrayList) al).iterator();
        while (it.hasNext()) {
            User usr = (User) (it.next());
            int index = al.indexOf(usr);
            al.remove(index);
            // it.remove();
        }
        System.out.println("Cleard");
    }
}

注意到上面代码中注释部分的上面2句,那就是异常出现的根源,我从ArrayList的一个对象al中移去了项目,然而Iterator对象it并不知道al中已经发生了变化,所以再继续遍历的时候会发生错误。正确的写法应该如注释行所示,然后注释行去掉上面的2行。


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值