0

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);
}
1
  • You are creating a new listOfCarIds in each iteration and discarding it. Perhaps you intended to initalise the field not the local variable before the loop. Commented Feb 26, 2016 at 14:13

2 Answers 2

6

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);
            }
Sign up to request clarification or add additional context in comments.

3 Comments

Why is this the case?
@java123999 Every time you are looping through the list in your code, you are declaring a new list and adding that item to it. After the loop completes, the list has gone out of scope and in inaccessible.
@java123999 I have added a more description, to make you understand
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.