Using an example:
Let say I have a class call Gun
.
I have another class call Bullet
.
Class Gun
has an
Edit:
Well, he edited his post.
If an Object inherits Iterable, you are given the ability to use the for-each loop as such:
for(Object object : objectListVar) {
//code here
}
So in your case, if you wanted to update your Guns and their Bullets:
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
}
}
First get your third Gun object:
Gun g = gunList.get(2);
Then iterate over the third gun's bullets:
ArrayList<Bullet> bullets = g.getBullets();
for(Bullet b : bullets) {
//necessary code here
}
We can do a nested loop to visit all the elements of elements in your list:
for (Gun g: gunList) {
System.out.print(g.toString() + "\n ");
for(Bullet b : g.getBullet() {
System.out.print(g);
}
System.out.println();
}
When using Java8 it would be more easier and a single liner only.
gunList.get(2).getBullets().forEach(n -> System.out.println(n));
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
}
You want to follow the same pattern as before:
for (Type curInstance: CollectionOf<Type>) {
// use currInstance
}
In this case it would be:
for (Bullet bullet : gunList.get(2).getBullet()) {
System.out.println(bullet);
}
for (Bullet bullet : gunList.get(2).getBullet()) System.out.println(bullet);