Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

java - Adding and object to a list inside a while loop

I'm trying to loop a list and that list have 4 arrays inside and each array have 7 values

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).

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Each time you are adding a Person you want to add a different person right?

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...