Using an example:
Let say I have a class call Gun.
I have another class call Bullet.
Class Gun has an ArrayList of Bullet.
To iterate through the Arraylist of Gun ..instead of doing this:
ArrayList<Gun> gunList = new ArrayList<Gun>();
for (int x=0; x<gunList.size(); x++)
System.out.println(gunList.get(x));
We can simply iterate through the ArrayList of Gun as such:
for (Gun g: gunList) System.out.println(g);
Now, I want to iterate and print out all Bullet of my 3rd Gun object:
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));
Now my question is: Instead of using the conventional for-loop, how do I printout the list of gun objects using the ArrayList iteration ?
Iterable(and we know thatListdoes) you can use afor-eachloop.