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

前端 未结 6 594
温柔的废话
温柔的废话 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:30

    Edit:

    Well, he edited his post.

    If an Object inherits Iterable, you are given the ability to use the for-each loop as such:

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

    So in your case, if you wanted to update your Guns and their Bullets:

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

    First get your third Gun object:

    Gun g = gunList.get(2);
    

    Then iterate over the third gun's bullets:

    ArrayList<Bullet> bullets = g.getBullets();
    
    for(Bullet b : bullets) {
         //necessary code here
    }
    
    0 讨论(0)
  • 2020-12-24 01:33

    We can do a nested loop to visit all the elements of elements in your list:

     for (Gun g: gunList) {
       System.out.print(g.toString() + "\n   "); 
       for(Bullet b : g.getBullet() {
          System.out.print(g);    
       }
       System.out.println(); 
     }
    
    0 讨论(0)
  • 2020-12-24 01:36

    When using Java8 it would be more easier and a single liner only.

        gunList.get(2).getBullets().forEach(n -> System.out.println(n));
    
    0 讨论(0)
  • 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<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
    }
    
    0 讨论(0)
  • 2020-12-24 01:49

    You want to follow the same pattern as before:

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

    In this case it would be:

    for (Bullet bullet : gunList.get(2).getBullet()) {
       System.out.println(bullet);
    }
    
    0 讨论(0)
  • 2020-12-24 01:52
    for (Bullet bullet : gunList.get(2).getBullet()) System.out.println(bullet);
    
    0 讨论(0)
提交回复
热议问题