To visit each nested node, you can do a tree traversal. There are several traversal orders to choose from:
- depth first, pre-order
- depth first, post-order
- breadth first
- ...
Here is some sample code for depth-first, pre-order printing of those someVariable
strings, each indented by the depth in the tree, and another function that performs a deep copy of the entire object structure:
import java.util.*;
public class A {
private String someVariable;
private List<A> innerObjects;
public A(String text) {
someVariable = text;
innerObjects = new ArrayList<A>();
}
public A add(String text) {
return add(new A(text));
}
public A add(A object) {
innerObjects.add(object);
return object;
}
public A deepCopy() {
A object = new A(someVariable);
for (A inner : innerObjects) {
object.add(inner.deepCopy());
}
return object;
}
public void deepPrint() {
deepPrint("");
}
public void deepPrint(String prefix) {
System.out.println(prefix + someVariable);
for (A object : innerObjects) {
object.deepPrint(prefix + " ");
}
}
}
And some driver code to test this:
public static void main(String[] args) {
A root = new A("world");
A europe = root.add("Europe");
europe.add("Germany");
europe.add("France");
A northAmerica = root.add("North America");
northAmerica.add("United States");
northAmerica.add("Canada");
A copy = root.deepCopy();
copy.deepPrint();
}