Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through an ArrayList of Objects of ArrayList of Objects?

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 ?

like image 260
user3437460 Avatar asked Jul 24 '14 20:07

user3437460


People also ask

How do you iterate through a list of objects?

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().

How many ways we can iterate ArrayList?

You can iterate a given ArrayList in 4 different ways.

Can you sort an ArrayList of objects in Java?

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.

Can you use for each loop with ArrayList?

We can use the Java for-each loop to iterate through each element of the arraylist.


1 Answers

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); } 
like image 126
unholysampler Avatar answered Sep 30 '22 19:09

unholysampler