数组未填充:添加方法使用不正确?(Array not populating: Incorrect use of add method?)

编程入门 行业动态 更新时间:2024-10-22 23:33:10
数组未填充:添加方法使用不正确?(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); }

更多推荐

本文发布于:2023-07-08 19:58:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1080232.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   不正确   方法   Array   method

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!