简体   繁体   中英

create java function to repeat adding object

The desired output is to be like below. Have the node class being serialized at the end so will turn the class into json string for me however the problem is the process need to be looped rather than hard coded.

 {"name":"Main","nodes":[{"name":"Tree","nodes":[{"name":"Branch","nodes":[{"name":"Stick","nodes":[{"name":"Leaf"}]}]}]}]}

I am trying to loop through this process so that I don't manually keep adding all the objects into each other.

    Node mainNode = new Node();
    mainNode.setName("Main");
    String directory = "Tree/Branch/Stick/Leaf";
    Node n1 = new Node();
    n1.setName("Tree");
    Node n2 = new Node();
    n2.setName("Branch");
    Node n3 = new Node();
    n3.setName("Stick");
    Node n4 = new Node();
    n4.setName("Leaf");

    n3.addNode(n4);
    n2.addNode(n3);
    n1.addNode(n2);
    mainNode.addNode(n1);

    Gson gson = new Gson();
    logger.info(gson.toJson(mainNode));

Node class

public class Node {
  public String name;
  public Node[] nodes;

  public Node(){}
  public Node(String name){
      this.name = name;
  }
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public Node[] getNodes() {
    return nodes;
}
public void setNodes(Node[] nodes) {
    this.nodes = nodes;
}
public void addNode(Node node){
    this.nodes = (Node[]) ArrayUtils.add(this.nodes, node);
}

Better add contructor with child node:

Node(String name, Node child) {
    this.name = name;
    if (child != null) {
        addChild(child);
    }
}

And define static recursive method:

public static Node getNodeTree(String[] leaves) {
        if (leaves.length == 1) {
            return new Node(leaves[0]);
        }

        return new Node(leaves[0], getNodeTree(Arrays.copyOfRange(leaves, 1, leaves.length)));
    }

And you will get what you want. And don't forget add check if leaves is null or empty array.

You could add a method that uses recursion...

public void addNodeToEnd(Node newNode)
{
    if(this.getNodes().length == 0)
    {
        this.addNode(newNode);
    }
    else
    {
        this.getNodes()[this.getNodes().length - 1].addNodeToEnd(newNode);
    }
}

//make sure you initialize your array of nodes
public Node(String name)
{
  this.name = name;
  this.nodes = new Node[1]; //or however many you want to store
}

here is a loop you can use after creating your main node

String[] names = directory.split("/");

for(int i = 0; i < names.length; i++)
{
    Node temp = new Node(names[i]);
    mainNode.addNode(temp);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM