在while循环内向列表中添加和对象 [英] Adding and object to a list inside a while loop

查看:121
本文介绍了在while循环内向列表中添加和对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试循环一个列表,该列表内部有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); 
}

当我打印人员列表时,列表中将包含具有相同名称,lastName和昵称的人员,而该列表中将包含具有相同值的相同对象.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆