举个例子:
假设我有一个类调用 Gun
。
我有另一个类调用 Bullet
。
类 Gun
有一个 Bullet
的 ArrayList。
要遍历 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);
现在,我想迭代并打印出我的第三个 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));
现在我的问题是:我如何使用 ArrayList 迭代打印出枪支对象列表,而不是使用传统的 for 循环?
最佳答案
您想遵循与以前相同的模式:
for (Type curInstance: CollectionOf<Type>) {
// use currInstance
}
在这种情况下,它将是:
for (Bullet bullet : gunList.get(2).getBullet()) {
System.out.println(bullet);
}
关于java - 如何遍历 ArrayList of Objects 的对象 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24943663/