Reputation: 7394
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
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
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