Java 如何遍历ArrayList of Objects的ArrayList?
使用示例: 假设我有一个班级呼叫Java 如何遍历ArrayList of Objects的ArrayList?,java,object,arraylist,iteration,Java,Object,Arraylist,Iteration,使用示例: 假设我有一个班级呼叫Gun。 我有另一个类调用Bullet 类Gun的数组列表为Bullet 要遍历Gun的数组列表,请执行以下操作: ArrayList<Gun> gunList = new ArrayList<Gun>(); for (int x=0; x<gunList.size(); x++) System.out.println(gunList.get(x)); 现在,我想迭代并打印出我的第三个枪对象的所有子弹: for (int x
Gun
。
我有另一个类调用Bullet
类Gun
的数组列表为Bullet
要遍历Gun
的数组列表,请执行以下操作:
ArrayList<Gun> gunList = new ArrayList<Gun>();
for (int x=0; x<gunList.size(); x++)
System.out.println(gunList.get(x));
现在,我想迭代并打印出我的第三个枪
对象的所有子弹
:
for (int x=0; x<gunList.get(2).getBullet().size(); x++) //getBullet is just an accessor method to return the arrayList of Bullet
System.out.println(gunList.get(2).getBullet().get(x));
对于(int x=0;x您希望遵循与以前相同的模式:
for (Type curInstance: CollectionOf<Type>) {
// use currInstance
}
编辑:
嗯,他编辑了他的文章
如果对象继承Iterable,则可以使用for each循环:
for(Object object : objectListVar) {
//code here
}
所以在你的情况下,如果你想更新你的枪和子弹:
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
}
}
然后迭代第三支枪的子弹:
ArrayList<Bullet> bullets = g.getBullets();
for(Bullet b : bullets) {
//necessary code here
}
ArrayList项目符号=g.getBullets();
用于(项目符号b:项目符号){
//这里有必要的代码
}
我们可以执行嵌套循环来访问列表中元素的所有元素:
for (Gun g: gunList) {
System.out.print(g.toString() + "\n ");
for(Bullet b : g.getBullet() {
System.out.print(g);
}
System.out.println();
}
int i=0;//用于确定何时在第三炮的计数器
对于(枪g:gunList){//对于列表中的每一支枪
System.out.println(g);//打印枪
如果(i==2){//如果你在第三枪
ArrayList子弹=g.getBullet();//获取枪中子弹的列表
对于(项目符号b:项目符号){//然后打印每个项目符号
系统输出打印ln(b);
}
i++;//别忘了增加你的计数器,这样你就知道你在下一枪了
}
当使用Java8时,它会更容易,而且只需要一个线性程序
gunList.get(2).getBullets().forEach(n -> System.out.println(n));
为什么您认为您的too案例之间存在差异?只要您的类实现了Iterable
(我们知道List
)你可以对每个循环使用一个。对于谁否决了这个问题,介意在这里放弃一个理由吗?我已经检查过了,以前没有人问过这个问题。我希望你能证明你否决我的理由是正确的。谢谢。对于任何善良的灵魂,如果你认为我的问题是正确的,请给我一个向上的投票来扭转这个不合理的否决投票。谢谢。你给了我我想要的东西。我试过了,效果很好。感谢所有提供答案的人。说真的吗?我认为一行代码通常不需要解释。特别是当问问题的人自己写下:“for(Gun g:gunList)System.out.println(g);”甚至gunList.get(2).getBullets().forEach(System.out::println);
。
Gun g = gunList.get(2);
ArrayList<Bullet> bullets = g.getBullets();
for(Bullet b : bullets) {
//necessary code here
}
for (Gun g: gunList) {
System.out.print(g.toString() + "\n ");
for(Bullet b : g.getBullet() {
System.out.print(g);
}
System.out.println();
}
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
}
gunList.get(2).getBullets().forEach(n -> System.out.println(n));