如何做一个for循环在一个嵌套的ArrayList? [英] How to do a for loop over a nested ArrayList?

查看:162
本文介绍了如何做一个for循环在一个嵌套的ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要使这个2D渲染引擎模块化尽我所能。我想出了,但还没有完成,绘制/更新精灵,这样我可以控制哪些精灵在对方面前的优先级列表。

这code通过每个优先级列表意味着循环并呈现在列表中的每个精灵。

  //我并不完全明白这是什么的,每个类型的循环一样。公共静态无效renderSprites(ArrayList的< ArrayList的< AbstractSprite>>优先){
    对于(ArrayList的< AbstractSprite>优先:优先){
        对于(AbstractSprite精灵:priorities.get(优先级)){           renderSprite(/ *我应该引用来获得相关精灵* /?);           //这是什么嵌套循环将是我最好的猜测,但它显然是行不通的。
          //有任何想法吗?
        }
    }
}


解决方案

for..each 结构遍历集合或数组中的每个元素。该结构是形式:

 的(类型的varName:[阵列||收藏]){
  //每次迭代varname是指集合/数组中指定的元素
}

在您的例子中,外环妥善建造,并分配的ArrayList 来为每次迭代优先级变量。内环不正确构造,因为要在的ArrayList 优先每个元素遍历,然而code试图从<$ C $使用元素C>优先级 的ArrayList 。下面code显示了适当的结构和替换的ArrayList 列表接口,这是preferred在使用具体类型的集合。

 公共静态无效renderSprites(列表&LT;名单,LT; AbstractSprite&GT;&GT;优先){
    对于(列表&LT; AbstractSprite&GT;优先:优先){
        对于(AbstractSprite精灵:优先级)){
           renderSprite(精灵);
        }
    }
}

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

解决方案

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

这篇关于如何做一个for循环在一个嵌套的ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆