ConcurrentModificationException如何解决

jiesiting 2013-01-14 02:54:40
public static void main(String[] args) {
List<Person> personDisList = new ArrayList<Person>();
Person person1 = new Person();
Person person2 = new Person();
person1.setId("1");
person2.setId("2");
personDisList.add(person1);
personDisList.add(person2);

List<Person> personList = new ArrayList<Person>();
for (int i=0; i<personDisList.size(); i++){
Person person = new Person();
person.setId(personDisList.get(i).getId());
if(personList.size() !=0){
for (Person personForeachPerson : personList) {
if(personForeachPerson.getId()!=person.getId()){
personList.add(person);
}
}
}else{
personList.add(person);
}
}
}

为什么会报如标题的错呢,求改错之后的详细代码,注:Person只是个JavaBean
...全文
373 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
xtfgy2012 2013-01-15
  • 打赏
  • 举报
回复
集合的循环就是循环,不要在循环的同时去做增删操作 另外要根据关键子判断是否同一个对象,优先考虑下用Map来存储 将Map的key设置成你的关键字,值是你的对象,这样判断方便
BadPattern 2013-01-15
  • 打赏
  • 举报
回复
使用迭代器Iterator
coralandbill 2013-01-15
  • 打赏
  • 举报
回复
package cn.com.mytest.test; import java.util.ArrayList; import java.util.List; import com.mytest.po.student.Student; public class Test1 { public static void main(String[] args) { List<Student> personDisList = new ArrayList<Student>(); Student person1 = new Student(); person1.setId(1); person1.setName("test1"); person1.setClassName("sfs"); person1.setAge(12); Student person2 = new Student(); person2.setId(2); person2.setName("test2"); person2.setClassName("231s"); person2.setAge(11); personDisList.add(person1); personDisList.add(person2); List<Student> personList = new ArrayList<Student>(); for (int i=0; i<personDisList.size(); i++){ Student person=new Student(); person.setId(personDisList.get(i).getId()); if(personList.size()!=0){ boolean bn=false; for (int j=0;j<personList.size();j++) { if(personDisList.get(i).getId()!=personList.get(j).getId());{ personList.add(personDisList.get(i)); break; } } }else{ personList.add(person); } System.out.println(personList.size()); } } } 楼主看看这是不是你要的代码;
healer_kx 2013-01-15
  • 打赏
  • 举报
回复
Google this Exception,IF you find a lot of people talking it, just find how to fix it. If not, your program must be wrong.
zlss_17 2013-01-15
  • 打赏
  • 举报
回复
引用 2 楼 dr8737010 的回复:
使用迭代器Iterator
+
龙四 2013-01-14
  • 打赏
  • 举报
回复
不可以在遍历ArrayList的时候还调用list的方法对其进行增删

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧