问题:
List<People> peopleList = new ArrayList();
People people = new People();
for(int i = 0 ; i < 10 ; i++){
people.setId("id" + i);
people.setAge("age" + i);
peopleList.add(people);
}
//输出结果都是
//id10
//age10
sout(peopleList);
原因
问题的产生在于,对象。对象中保存的都是地址。
People 对象在循环前,便新建成功,分配了内存空间,不再发生变化。
每次赋值的过程,都是在同一个内存空间,更改保存的地址。
peopleList.add(people);
//其中,List 中保存的是,people 这个对象。
//在循环赋值的过程中,people 中的保存的值(所指向的地址)一直在发生变化。
for(int i = 0 ; i < 10 ; i++){
people.setId("id" + i);
people.setAge("age" + i);
}
所以最后存入 List 中的对象,都是最后输入的属性
正确的做法
List<People> peopleList = new ArrayList();
for(int i = 0 ; i < 10 ; i++){
//将对象的定义放在循环里,每次都是一个新的对象
People people = new People();
people.setId("id" + i);
people.setAge("age" + i);
peopleList.add(people);
}
sout(peopleList);
此时,每次循环都会新建一个对象,分配一个新的内存空间。