所需的输出如下所示。让节点类在最后被序列化,所以我会把类转换为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);
}
答案 0 :(得分:1)
最好使用子节点添加构造函数:
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)));
}
你会得到你想要的东西。如果叶子为空或空数组,请不要忘记添加检查。
答案 1 :(得分:0)
您可以添加一个使用递归的方法......
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
}
这是一个在创建主节点后可以使用的循环
String[] names = directory.split("/");
for(int i = 0; i < names.length; i++)
{
Node temp = new Node(names[i]);
mainNode.addNode(temp);
}