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 ?
Obtain an iterator to the start of the collection by calling the collection's iterator() method. Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true. Within the loop, obtain each element by calling next().
You can iterate a given ArrayList in 4 different ways.
In the main() method, we've created an array list of custom objects list, initialized with 5 objects. For sorting the list with the given property, we use the list's sort() method. The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator.
We can use the Java for-each loop to iterate through each element of the arraylist.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With