trd3v3lop trd3v3lop - 3 months ago 8
Java Question

Iterating ArrayList<Class> inside that Class

I want to iterate all of the items inside main arraylist.

Output is so far I gone.. As you can see it doesn't show a3, a3_1 and a3_2

Thanks in advance!

Here is my code:

addModel adds Model to the Araylist inside that object. It is a method of Model class.

MODEL

public class Model {
String name;
String surname;
ArrayList<Model> arr = new ArrayList<Model>();

....//Constructor, getters,setters, toString\\

}


MAIN

public class Test{
public static void main(String[] args) {
ArrayList<Model> list = new ArrayList<Model>();

Model a= new Model("1", "1");
list.add(a);

Model a2 = new Model("2", "2");
list.add(a2);

Model a2_1 = new Model("2_1", "2_1");
a2.addModel(a2_1);

Model a2_2 = new Model("2_2", "2_2");
a2.addModel(a2_2);

Model a2_3 = new Model("2_3", "2_3");
a2.addModel(a2_3);

Model a3 = new Model("3", "3");
list.add(a3);

Model a3_1 = new Model("3_1", "3_1");
a3.addModel(a3_1);

Model a3_2 = new Model("3_2", "3_2");
a3.addModel(a3_2);


iterate(list,0,true);
System.out.println("\nEnd");
}

public static int iterate(ArrayList<Model> m, int i, boolean isNew){
System.out.println(m.get(i).toString());

if(!m.get(i).getArr().isEmpty()){
Model mx = m.get(i);
ArrayList<Model> nextArray=mx.getArr();
if(isNew)
return iterate(nextArray, 0,true);
else
return iterate(nextArray, i,false);
}
else{
return iterate(m, i+1,true);
}
}
}


OUTPUT

{ name: 1 surname: 1}

{ name: 2 surname: 2}
Exception in thread "main"
{ name: 2_1 surname: 2_1}

{ name: 2_2 surname: 2_2}

{ name: 2_3 surname: 2_3}
java.lang.IndexOutOfBoundsException: Index: 3, Size: 3

Answer

Another option

public static void iterate(ArrayList<Model> modelList) {

    if (modelList == null) return;

    for (Model model : modelList) {
        System.out.println(model.toString());
        iterate(model.getArr());
    }
}
Comments