java-如何遍历对象的ArrayList的对象的ArrayList?

使用示例:

假设我有一个班级叫Bullet。我还有另一个班级叫Gun

Bullet的ArrayList为Gun

要遍历Bullet的Arraylist而不是这样做:

ArrayList<Gun> gunList = new ArrayList<Gun>();
for (int x=0; x<gunList.size(); x++)
    System.out.println(gunList.get(x));

我们可以像这样简单地遍历Bullet的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));

现在我的问题是:与使用常规的for循环不同,如何使用ArrayList迭代打印出枪支对象列表?

user3437460 asked 2020-07-22T16:25:48Z
6个解决方案
43 votes

您要遵循与以前相同的模式:

for (Type curInstance: CollectionOf<Type>) {
  // use currInstance
}

在这种情况下,它将是:

for (Bullet bullet : gunList.get(2).getBullet()) {
   System.out.println(bullet);
}
unholysampler answered 2020-07-22T16:26:12Z
9 votes

编辑:

好吧,他编辑了自己的帖子。

如果对象继承了Iterable,则可以使用for-each循环,例如:

for(Object object : objectListVar) {
     //code here
}

因此,如果您要更新枪支及其子弹,请执行以下操作:

for(Gun g : guns) {
     //invoke any methods of each gun
     ArrayList<Bullet> bullets = g.getBullets()
     for(Bullet b : bullets) {
          System.out.println("X: " + b.getX() + ", Y: " + b.getY());
          //update, check for collisions, etc
     }
}

首先获取第三个Gun对象:

Gun g = gunList.get(2);

然后遍历第三枪的子弹:

ArrayList<Bullet> bullets = g.getBullets();

for(Bullet b : bullets) {
     //necessary code here
}
0-4930-42390eo23o2e0-23oe0-23o answered 2020-07-22T16:26:54Z
6 votes

当使用Java8时,它会更容易,并且只有一个衬里。

    gunList.get(2).getBullets().forEach(n -> System.out.println(n));
Ray A answered 2020-07-22T16:27:14Z
3 votes
for (Bullet bullet : gunList.get(2).getBullet()) System.out.println(bullet);
Tsotne Tabidze answered 2020-07-22T16:27:29Z
1 votes

我们可以做一个嵌套循环来访问列表中所有元素的元素:

 for (Gun g: gunList) {
   System.out.print(g.toString() + "\n   "); 
   for(Bullet b : g.getBullet() {
      System.out.print(g);    
   }
   System.out.println(); 
 }
Thorn answered 2020-07-22T16:27:49Z
1 votes
int i = 0; // Counter used to determine when you're at the 3rd gun
for (Gun g : gunList) { // For each gun in your list
    System.out.println(g); // Print out the gun
    if (i == 2) { // If you're at the third gun
        ArrayList<Bullet> bullets = g.getBullet(); // Get the list of bullets in the gun
        for (Bullet b : bullets) { // Then print every bullet
            System.out.println(b);
        }
    i++; // Don't forget to increment your counter so you know you're at the next gun
}
Andrew Orobator answered 2020-07-22T16:28:06Z
translate from https://stackoverflow.com:/questions/24943663/how-to-iterate-through-an-arraylist-of-objects-of-arraylist-of-objects