Using an example:
假设我有一个课程电话 Gun
. 我有另一个 class 电话 Bullet
.
类 Gun
的ArrayList为 Bullet
.
迭代 Gun
的Arraylist ..而不是这样做:
ArrayList<Gun> gunList = new ArrayList<Gun>();
for (int x=0; x<gunList.size(); x++)
System.out.println(gunList.get(x));
我们可以简单地遍历 Gun
的ArrayList:
for (Gun g: gunList) System.out.println(g);
现在,我想迭代并打印出我的第3个 Gun
对象的所有 Bullet
:
for (int x=0; x<gunList.get(2).getBullet().size(); x++) //getBullet is just an accessor method to return the arrayList of Bullet
System.out.println(gunList.get(2).getBullet().get(x));
Now my question is: 如何使用ArrayList迭代打印输出枪对象列表,而不是使用传统的for-loop?
6 回答
您想要遵循与以前相同的模式:
在这种情况下,它将是:
编辑:
好吧,他编辑了他的帖子 .
如果Object继承了Iterable,则可以使用for-each循环:
所以在你的情况下,如果你想更新你的枪支和他们的子弹:
首先得到你的第三个枪对象:
然后迭过第三枪的子弹:
使用Java8时,它将更容易,只有一个单行 .
我们可以做一个嵌套循环来访问列表中元素的所有元素: