gpt4 book ai didi

java - 创建java函数来重复添加对象

转载 作者:行者123 更新时间:2023-11-30 10:37:54 25 4
gpt4 key购买 nike

所需的输出如下所示。让节点类在最后被序列化,以便将类转换为 json 字符串,但问题是该过程需要循环而不是硬编码。

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

我正在尝试循环执行此过程,这样我就不会手动将所有对象相互添加。

    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));

节点类

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);
}

最佳答案

最好添加带有子节点的构造器:

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

并定义静态递归方法:

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)));
}

你会得到你想要的。并且不要忘记添加检查 leaves 是否为 null 或空数组。

关于java - 创建java函数来重复添加对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39987025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com