Search code examples
javaclasstreenodes

Is it possible to create a tree structure with classes as its node?


I am trying to implement a custom tree structure in java. I want my tree to have its nodes of type class (i.e.,) each node in my tree should represent a class and should point to its child nodes. Is this possible to create? If not, is there any other way of implementing such a structure?

P.S. sorry if the question seems illogical :-|


Solution

  • You have to wrap the Class objects to be able to point to their children.

    class CustomTree {
        Node root;
    
        public CustomTree(Node root) {
            this.root = root;
        }
    }
    
    class Node {
        Class value;
        List<Node> children;
    
        public Node(Class value) {
            this.value = value;
            children = new ArrayList<>();
        }
    
        public void addChild(Class clazz) {...}
    }