How to do a for loop over a nested ArrayList?

Sam*_*lls 5 java for-loop 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?
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Kev*_*sox 1

for..each构造迭代集合或数组中的每个元素。其构造形式如下:

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

在您的示例中,外部循环已正确构建,并将为每次迭代将 分配ArrayList给变量。priority内部循环未正确构造,因为您想要迭代ArrayList优先级中的每个元素,但是代码尝试使用priority ArrayList. 以下代码显示了正确的结构,并将 替换ArrayListList接口,这优于使用集合的具体类型。

public static void renderSprites(List<List<AbstractSprite>> priorities){
    for (List<AbstractSprite> priority : priorities){
        for(AbstractSprite sprite : priority)){
           renderSprite(sprite);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)