当前位置:编程学习 > JAVA >>

ConcurrentModificationException如何解决

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 list --------------------编程问答-------------------- 不可以在遍历ArrayList的时候还调用list的方法对其进行增删 --------------------编程问答-------------------- 使用迭代器Iterator --------------------编程问答-------------------- 集合的循环就是循环,不要在循环的同时去做增删操作

另外要根据关键子判断是否同一个对象,优先考虑下用Map来存储

将Map的key设置成你的关键字,值是你的对象,这样判断方便 --------------------编程问答--------------------
引用 2 楼 dr8737010 的回复:
使用迭代器Iterator

+ --------------------编程问答-------------------- 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. --------------------编程问答-------------------- 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());
  }
 }
 
}

楼主看看这是不是你要的代码;
补充:Java ,  Java SE
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,