在 while 循环中将对象添加到列表中 [英] Adding and object to a list inside a while loop
问题描述
我正在尝试循环一个列表,该列表中有 4 个数组,每个数组有 7 个值
I'm trying to loop a list and that list have 4 arrays inside and each array have 7 values
我正在循环列表,然后当我从列表中获取一个数组时,因为我知道该数组有多少个值,所以我像这样分配每个数组索引:personObject.setName(String.valueOf(myArray[0)])
然后在 while 循环的末尾,我将 personObject 添加到 Persons 列表中,如下所示:listOfPersons.add(personObject).
I am looping the list and then when I get an array from the list, since I know how many values have the array I assign each array index like this: personObject.setName(String.valueOf(myArray[0])
and then at the end of the while loop I add to a list of Persons the personObject like this: listOfPersons.add(personObject).
我的问题是我的列表只填充了相同的对象,我知道我循环的列表中的 4 个数组具有不同的值,这是我的代码:
My problem is that my list only gets populate with the same object and I know that the 4 arrays inside the list that I'm looping have different values, here is my code:
ArrayList<Object> objectList= null;
objectList= _serviceVariable.getObjects(); <--- this works it returns a list with 4 arrays all with diferent values
Person myPerson = new Person();
List<Person> personsList = new List<Person>;
Iterator<Object> itr = objectList.iterator();
while(itr.hasNext())
{
Object[] innerObj = (Object[]) itr.next();
myPerson.setName(String.valueOf(innerObj [0])
myPerson.setLastName(String.valueOf(innerObj [1])
myPerson.setNickName(String.valueOf(innerObj [2])
personsList.add(myPerson);
}
当我打印我的人员列表时,里面全是同名的人,姓氏和昵称,是一个充满具有相同值的相同对象的列表.
when I print my persons list is full of persons with the same name, lastName and nick name, is a list full of the same objects with the same values.
推荐答案
每次添加 Person
时,您都想添加一个 不同的 人对吗?
Each time you are adding a Person
you want to add a different person right?
因此,您应该每次在循环中创建一个 new
Person
对象.不要只在循环之外创建一个您不断更改其数据的数据.
Therefore, you should create a new
Person
object inside your loop every time.
Not create only one outside of the loop whose data you just keep changing.
// NOT HERE Person myPerson = new Person();
// ...
while(itr.hasNext()) {
Object[] innerObj = (Object[]) itr.next();
Person myPerson = new Person(); // HERE you create a new Person
myPerson.setName(String.valueOf(myArray[0]);
myPerson.setLastName(String.valueOf(myArray[1]);
myPerson.setNickName(String.valueOf(myArray[2]);
personsList.add(myPerson); // add the new person to the list
}
这篇关于在 while 循环中将对象添加到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!