Question

I have a class like this:

class Foo {
    public String name = "";
    public ArrayList<Foo> children = new ArrayList<Foo>();
}

Now, I have about two thousand of these 'Foo' objects stored in ArrayList, and they are related to each other as you can see from the snippet above. Now, these relations may be cyclic: A may have a child B, which may have child C, which may have child A. What I want to do is to print out a tree of these relations while ignoring the cyclic relations, like this:

ObjA
  ObjB
    ObjC
ObjD
  ObjB
    ObjA

How can I do this? It doesn't have to be fast or anything, this tree would be mainly for ensuring the results of my program.

Was it helpful?

Solution

Foo needs a print method that prints its contents and then calls the print method of the Foo it's pointing to. Print takes a HashSet that contains all Foo objects that have been traversed. If next is in visited then it's part of a cycle and you don't call its print method.

class Foo {
    Foo next;
    void print(HashSet<Foo> visited) {
        System.out.println("this Foo's ID or whatever it is you're printing");
        visited.add(this);
        if(next != null && !visited.contains(next)) {
            next.print(visited);
        }
    }
}

You may also want to pass in an int parameter that determines the level of indentation - if indent equals 4 then print 4 spaces before the System.out.println, and increment indent by 2 or 4 or whatever when you call print on next.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top