java.util.ConcurrentModificationException异常 解决方法
2011-09-23 09:27
681 查看
原文:http://blog.sina.com.cn/s/blog_48dc562301000d2b.html
今天写一个程序的时候遇到了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行。
今天写一个程序的时候遇到了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行。
相关文章推荐
- java.util.ConcurrentModificationException 异常的解决方法
- java.util.ConcurrentModificationException异常解决方法
- java.util.ConcurrentModificationException 异常解决的方法及原理
- java.util.ConcurrentModificationException异常解决方法
- java.util.ConcurrentModificationException异常参考解决方法
- Java ConcurrentModificationException异常原因和解决方法
- Java Concurrentmodificationexception异常原因和解决方法
- Java ConcurrentModificationException异常原因和解决方法
- Java ConcurrentModificationException异常原因和解决方法
- java.util.ConcurrentModificationException原因及解决方法
- Java ConcurrentModificationException异常原因和解决方法
- Java ConcurrentModificationException异常原因和解决方法
- Java ConcurrentModificationException异常原因和解决方法
- Java ConcurrentModificationException异常原因和解决方法
- 【转载】Java并发编程9:Java ConcurrentModificationException异常原因和解决方法
- Java ConcurrentModificationException异常原因和解决方法
- java.util.ConcurrentModificationException异常的解决办法
- java.util.ConcurrentModificationException异常的解决实例
- Java ConcurrentModificationException异常原因和解决方法
- java.util.ConcurrentModificationException的解决方法