数组未填充:添加方法使用不正确?(Array not populating: Incorrect use of add method?)
在我的for-loop中,我试图添加与具有特定状态的persons相关联的所有car IDS 。
我的代码编译并运行,但是arrayList:listOfCarIds的大小保持为0 。 即似乎没有添加任何东西
我是如何实现这一点的?
for(int i=0 ; i < personsWithStatus.size() ; i++) { idOfCarRelatingToPerson = personsWithStatus.get(i).getCarId(); List<String> listOfCarIds = new ArrayList(); listOfCarIds.add(idOfCarRelatingToPerson); }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); }最满意答案
在外部声明您的ArrayList因为您在for循环中声明的ArrayList将每次初始化并且仅在for循环内具有范围。
List<String> listOfCarIds = new ArrayList(); for(int i=0 ; i < personsWithStatus.size() ; i++) { idOfCarRelatingToPerson = personsWithStatus.get(i).getCarId(); listOfCarIds.add(idOfCarRelatingToPerson); }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); }更多推荐
发布评论