7092

How to make a tree having multiple type of nodes and each node can have multiple child nodes in java

Basically i am trying to implement something like this, where partner node is of say "type1", client node is of "type2" and user nodes is of "type3". And each of the nodes can have multiple number of child nodes. So Partner1 can have any number of client nodes under it, similarly client nodes can have any number of users under it.

<img src=https://www.e-learn.cn/content/wangluowenzhang/"https://i.stack.imgur.com/5VTEW.png" alt="enter image description here">

I have started the implementation but i am stuck now.The code which i have written is as follows. <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code">

public class ClientProperty {
    public class Root{}         //NodeType1

    public class Partner{       //NodeType2
        public String partner_id;
        public String partner_name;
        public int partner_node_id;

        public Partner(String partner_id,String partner_name,int partner_node_id){
            this.partner_id = partner_id;
            this.partner_name = partner_name;
            this.partner_node_id = partner_node_id;
        }
    }

    public class Clients{       //NodeType3
        public String client_name;
        public String client_id;
        public int client_node_id;
        public Map<Enum,List<Enum>> clientproperty = new HashMap<Enum,List<Enum>>();

        public Clients(String client_name, String client_id, int client_node_id,Map<Enum,List<Enum>> clientproperty){
            this.client_name = client_name;
            this.client_id = client_id;
            this.client_node_id = client_node_id;
            this.clientproperty = clientproperty;
        }
    }
    public class Users{         //NodeType4
        public String user_name;
        public String user_id;
        public int user_node_id;

        public Users(String user_id,String user_name, int user_node_id){
            this.user_id = user_id;
            this.user_name = user_name;
            this.user_node_id = user_node_id;
        }
    }
    public class Node{
        Node next;
        Object nodes;

        public Node(){
            next = null;
        }

        public Node(Object nodes, Node next){
            this.nodes = nodes;
            this.next = next;
        }
    }
}


Let me know if some insights is required

Answer1:

First some more unspecific things:

You want to read about <strong>data encapsulation</strong>. Putting all <strong>public</strong> fields on your classes is simply wrong. You actually want to hide such information as far as possible.

Then you want to read about <strong>java coding style conventions</strong>; as you are violating quite some of them (which simply doesn't help when you show your code to more experienced java coders).

Finally, most important: you want to read quite a bit about <strong>OO design</strong> in general (I recommend "Agile practices" by Robert Martin; there is a free PDF of the "C# version" of that book):

It starts wit the fact that

a) being a client/user is a "different responsibility" than

b) being some element in a graph

In other words: you are putting way too many "roles" into your classes.

Meaning: you want to introduce various kinds of abstractions. For example:

interface GraphNode<N, C extends GraphNode> { N getNodeContent(); List<C> getChildrenNodes(); }

Now you can express: any "node" does have some content (which could be a User or Client or whatever object); and it has a list (or set) of children, that are also "nodes".

Answer2:

Here I am providing you a high-level design, you have to give the implementation of getNext() and getChildren() as per your requirement. I hope It may help you, Let me know If you have any other thought.

// As all the entities are a kind of Node , so this interface should be implemented by all the entities . You can put some more methods in this interface, If required to be a Node type. interface Node { Node getNext(); List<? extends Node> getChildren(); } class Root implements Node { private List<Partner> partners; @Override /*Implementation required*/ public Root getNext() { return null; // Return next node } @Override /*Implementation required*/ public List<Partner> getChildren() { return partners; } } class Partner implements Node { private List<Client> clients; @Override /*Implementation required*/ public Partner getNext() { return null; // Return next node } @Override /*Implementation required*/ public List<Client> getChildren() { return clients; } } class Client implements Node { private List<User> users; @Override /*Implementation required*/ public Client getNext() { return null; // Return next node } @Override /*Implementation required*/ public List<User> getChildren() { return users; } } //As per your requirement, User class is leaf node, so you can return null in getChildren() call; class User implements Node { private List<? extends Node> children; @Override /*Implementation required*/ public User getNext() { return null; // Return next node } @Override /*Implementation required*/ public List<? extends Node> getChildren() { return children; } }

<strong>Note</strong>: Its a high level design. With this design, you can introduce more types in your application, if required in future.

Recommend

  • Can't restore packages on macOS Sierra
  • scala.collection.Seq doesn't work on Java
  • Removing Any Non-Specified Characters from an Excel Spreadsheet using a Macro
  • Extract string between xml tags in android without parsing the xml
  • Writing dataframe to postgres database
  • Windows Mercurial global keychain
  • ASP.Net check if user is internal or external
  • How do I write an item to a DynamoDb with the AWS DynamoDB DocumentClient?
  • Rails 5 - Google Maps - Javascript error - initMap is not a function - fixing one js issue creates a
  • Javascript: Looping through an array to create listeners, issue with call by reference and value?
  • How to add the custom button on google's(device) native application in android?
  • How to Add Polymorphic Comments to Feed?
  • Detecting # in Scheme list
  • Request response issues in biztalk
  • In loopback documentation what does variable 'cb' stands for?
  • User messaging system
  • KnockoutObservableArray with typed elements in TypeScript
  • Simple linked list-C
  • Update Google Maps traffic layer without page reloading
  • Image map in Flex
  • Updating both a ConcurrentHashMap and an AtomicInteger safely
  • Laravel: Getting Session ID oddly truncates when using foreach
  • Entity Framework Code First TPC Inheritance Self-Referencing Child Class
  • CakePHP ACL tutorial initDB function warnings
  • D3 nodes and links from JSON with nested arrays of children
  • C++ Partial template specialization - design simplification
  • Jenkins: How To Build multiple projects from a TFS repository?
  • How to add a column to a Pandas dataframe made of arrays of the n-preceding values of another column
  • script to move all files from one location to another location
  • Cassandra Data Model
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • Codeigniter doesn't let me update entry, because some fields must be unique
  • How do I configure my settings file to work with unit tests?
  • LevelDB C iterator
  • Is it possible to post an object from jquery to bottle.py?
  • Running Map reduces the dimensions of the matrices
  • How to get NHibernate ISession to cache entity not retrieved by primary key
  • How can i traverse a binary tree from right to left in java?
  • Android Heatmap on canvas or ImageView