I have a Foo object that has a field referencing a list of Bar objects. Each Bar object in a list of Bar references a next Foo object. The idea is to have a list of Foo objects, each one with a list of Bar pointing to different Foo objects in the list (i.e., foo1 has pointers to foo2 and foo5). The last Foo object points to null. In the example below there are two Foo instances: foo1 points to foo2, and foo2 points to null.
If I want to construct a list of linked Foo objects, I have to start from the last object and build it in reverse. Can I do this recursively?
public class Foo {
private final String id;
private final List<Bar> barList;
public Foo(String id, List<Bar> barList) {
this.id = id;
this.barList = barList;
}
public String getId() {
return id;
}
public List<Bar> getBarList() {
return barList;
}
}
public class Bar {
private final Foo nextFoo;
public Bar(Foo nextFoo) {
this.nextFoo = nextFoo;
}
public Foo getNextFoo() {
return nextFoo;
}
}
public class FooListBuilder {
public static void main(String[] args) {
buildFoosInReverse();
// buildFoosRecursively();
}
public static void buildFoosInReverse() {
List<Foo> fooList = new ArrayList<Foo>();
Bar bar2 = new Bar(null);
List<Bar> bar2List = new ArrayList<Bar>();
bar2List.add(bar2);
Foo foo2 = new Foo("2", bar2List);
Bar bar1 = new Bar(foo2);
List<Bar> bar1List = new ArrayList<Bar>();
bar1List.add(bar1);
Foo foo1 = new Foo("1", bar1List);
fooList.add(foo1);
fooList.add(foo2);
System.out.println(fooList);
}
}