首页 文章

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

提问于
浏览
38

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 回答

  • 3

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

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

    在这种情况下,它将是:

    for (Bullet bullet : gunList.get(2).getBullet()) {
       System.out.println(bullet);
    }
    
  • 1

    编辑:

    好吧,他编辑了他的帖子 .

    如果Object继承了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 g = gunList.get(2);
    

    然后迭过第三枪的子弹:

    ArrayList<Bullet> bullets = g.getBullets();
    
    for(Bullet b : bullets) {
         //necessary code here
    }
    
  • 38

    使用Java8时,它将更容易,只有一个单行 .

    gunList.get(2).getBullets().forEach(n -> System.out.println(n));
    
  • 1
    for (Bullet bullet : gunList.get(2).getBullet()) System.out.println(bullet);
    
  • 7

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

    for (Gun g: gunList) {
       System.out.print(g.toString() + "\n   "); 
       for(Bullet b : g.getBullet() {
          System.out.print(g);    
       }
       System.out.println(); 
     }
    
  • 6
    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
    }
    

相关问题