How to iterate through an ArrayList of Objects of ArrayList of Objects?

前端 未结 6 635
温柔的废话
温柔的废话 2020-12-24 01:18

Using an example:

Let say I have a class call Gun. I have another class call Bullet.

Class Gun has an

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-24 01:37

    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 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
    }
    

提交回复
热议问题