Home > Software design >  How to create a tree like structure with a List<CustomType> parameter in java constructor
How to create a tree like structure with a List<CustomType> parameter in java constructor

Time:04-05

I have a class Org that has name and a list of tasks and I want to print a list of tasks under each name in a tree like structure using the class constructor:
name -> A tasks - > B, C, name ->B tasks - > D, E, name -> C, tasks -> F,G

        A
       / \
     B     C
    / \   / \
   D   E  F  G


Here is the class structure:

static class Org {
        char name;
        List<Org> tasks;

        Org(char name, List<Org> tasks){
            this.name = name;
            this.tasks = tasks;
        }

I read this but it does not apply to what I'm doing. Here is what I tried

 List<Org> org = new Org('A', new ArrayList<Org>('B','C')); // for the first level
 org.add('B', new ArrayList<Org>('D','E')); // for the second level
 org.add('C', new ArrayList<Org>('F','G')); // for the third level


This does not work because the second parameter in the constructor expects an Org type and not a char type. How would you create such a tree using this constructor? Any help would be appreciated.

CodePudding user response:

For these problems, we should tackle it bottom up.

Org orgG = new Org('G', Arrays.asList());
Org orgF = new Org('F', Arrays.asList());
Org orgE = new Org('E', Arrays.asList());
Org orgD = new Org('D', Arrays.asList());
        
Org orgC = new Org('C', Arrays.asList(orgF, orgG));
Org orgB = new Org('B', Arrays.asList(orgD, orgE));
Org orgA = new Org('A', Arrays.asList(orgC, orgB));

With this, if Org has empty list means it is a leaf node (no child for it).

CodePudding user response:

You have to start from the bottom up, constructing the child object and passing it to the parent constructor. For the sake of brevity, I'll substitute Org... for List<Org>:

new Org('A',
    new Org('B',
        new Org('D'), new Org('E')),
    new Org('C',
        new Org('F'), new Org('G')))

CodePudding user response:

For the benefit of anyone who faces a similar issue, I was able to get what I needed with this based on the comments and answers provided by contributors.

            Org orgG = new Org('G', new ArrayList());
            Org orgF = new Org('F', new ArrayList());
            Org orgE = new Org('E', new ArrayList());
            Org orgD = new Org('D', Arrays.asList(orgH,orgI));
            Org orgC = new Org('C', Arrays.asList(orgF,orgG));
            Org orgB = new Org('B', Arrays.asList(orgD,orgE));
            Org orgA = new Org('A', Arrays.asList(orgB,orgC));
  • Related