Sam Walls
Sam Walls

Reputation: 185

How to do a for loop over a nested ArrayList?

I'm going to make this 2D rendering engine as modular as I possibly can. I've come up with, but haven't yet finished, a priority list for drawing/updating sprites, so that I can control which sprites are in front of each other.

This code is meant to loop through each priority list and render every sprite in that list.

//I don't entirely understand what this for-each type of loop does.

public static void renderSprites(ArrayList<ArrayList<AbstractSprite>> priorities){
    for (ArrayList<AbstractSprite> priority : priorities){
        for(AbstractSprite sprite : priorities.get(priority)){

           renderSprite(/* what should I reference to get the relevant sprite? */);

           //this is my best guess at what the nested loop would be, but it obviously doesn't work.
          //any ideas?
        }
    }
}

Upvotes: 5

Views: 7904

Answers (3)

fastcodejava
fastcodejava

Reputation: 41087

You are mostly there. You should have :

public static void renderSprites(List<List<AbstractSprite>> priorities){
    for (List<AbstractSprite> priority : priorities) { // You have priority here
        for (AbstractSprite sprite : priority) { // Now loop over priority to get sprite
           renderSprite(sprite);
         }
    }
}

Upvotes: 1

C.B.
C.B.

Reputation: 8326

Should simply be

for (ArrayList<AbstractSprite> priority : priorities){
    for(AbstractSprite sprite : priority){
        renderSprite(sprite);
    }
}

This assumes that the priorities arraylist is sorted in order from high to low priority, so you are rendering the sprites with the highest priority.

Remember that the get() method of an ArrayList expects an int which represents the index of the element you want to access. For-each loops are implemented to make indexing opaque to the user and simply iterate through the Collection instead.

Upvotes: 4

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

The for..each construct iterates over every element in a collection or an array. The construct is in the form:

for(Type varName : [Array || Collection]){
  //for each iteration varName is assigned an element in the collection/array
}

In your example the outer loop is properly constructed and will assign the ArrayList to the priority variable for each iteration. The inner loop is not properly constructed since you want to iterate over each element in the ArrayList priority, however the code attempts to use an element from the priority ArrayList. The following code shows the proper structure and replaces the ArrayList with the List interface, which is preferred over using the concrete type of the collection.

public static void renderSprites(List<List<AbstractSprite>> priorities){
    for (List<AbstractSprite> priority : priorities){
        for(AbstractSprite sprite : priority)){
           renderSprite(sprite);
        }
    }
}

Upvotes: 1

Related Questions