java123999
java123999

Reputation: 7394

Array not populating: Incorrect use of add method?

In my for-loop below I am trying to add all car IDS associated to a persons with a certain status.

My code compiles and runs, however the size of arrayList: listOfCarIds is remaining 0. I.e. nothing seems to be added

Is there a mistake in how I am implementing this?

for(int i=0 ; i < personsWithStatus.size() ; i++)
{
  idOfCarRelatingToPerson = personsWithStatus.get(i).getCarId();

  List<String> listOfCarIds = new ArrayList();

  listOfCarIds.add(idOfCarRelatingToPerson);
}

Upvotes: 0

Views: 62

Answers (2)

Pragnani
Pragnani

Reputation: 20155

Declare your ArrayList outside as the ArrayList you have declared inside the for loop will initialize every time and has the scope within the for loop only.

  List<String> listOfCarIds = new ArrayList();
for(int i=0 ; i < personsWithStatus.size() ; i++) {
       idOfCarRelatingToPerson = personsWithStatus.get(i).getCarId();
       listOfCarIds.add(idOfCarRelatingToPerson);
            }

Upvotes: 6

David Glickman
David Glickman

Reputation: 790

You are declaring your ArrayList in the loop. Each time it goes through the loop it resets listOfCarIDs to a blank ArrayList.

Declare the ArrayList outside the loop, and only use the loop to add to it.

Upvotes: 1

Related Questions