---
title: "[DEBUG]java.util.ConcurrentModificationException"
author: "ilusm"
date: "2008-06-05T09:06:00Z"
tags: []
slug: "debug-java-util-concurrentmodificationexception"
draft: false
lastmod: "2008-06-05T09:06:00Z"
id: 232240
url: "https://ilusm.iteye.com/blog/232240"
---

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