Ответ 1
Вы хотите следовать той же схеме, что и раньше:
for (Type curInstance: CollectionOf<Type>) {
// use currInstance
}
В этом случае это будет:
for (Bullet bullet : gunList.get(2).getBullet()) {
System.out.println(bullet);
}
Используя пример:
Скажем, у меня есть вызов класса Gun
.
У меня есть еще один вызов класса Bullet
.
Класс Gun
имеет ArrayList Bullet
.
Чтобы выполнить итерацию через Arraylist Gun
.. вместо этого:
ArrayList<Gun> gunList = new ArrayList<Gun>();
for (int x=0; x<gunList.size(); x++)
System.out.println(gunList.get(x));
Мы можем просто перебрать через ArrayList Gun
как таковой:
for (Gun g: gunList) System.out.println(g);
Теперь я хочу повторить и распечатать все Bullet
моего третьего объекта Gun
:
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));
Теперь мой вопрос: Вместо использования обычного цикла for-loop, как распечатать список объектов оружия с помощью итерации ArrayList?
Вы хотите следовать той же схеме, что и раньше:
for (Type curInstance: CollectionOf<Type>) {
// use currInstance
}
В этом случае это будет:
for (Bullet bullet : gunList.get(2).getBullet()) {
System.out.println(bullet);
}
При использовании Java8 было бы проще и только один лайнер.
gunList.get(2).getBullets().forEach(n -> System.out.println(n));
Edit:
Ну, он отредактировал свой пост.
Если объект наследует 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
}
}
Сначала получите свой третий объект Gun:
Gun g = gunList.get(2);
Затем повторите три пули пули:
ArrayList<Bullet> bullets = g.getBullets();
for(Bullet b : bullets) {
//necessary code here
}
for (Bullet bullet : gunList.get(2).getBullet()) System.out.println(bullet);
Мы можем сделать вложенный цикл для посещения всех элементов элементов в вашем списке:
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
}