如何在java中创建自己的树?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21718669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create own tree in java?
提问by Sathesh
I want to know how to create own tree in java, it consists of eight sub-nodes and in each sub-node it having many sub-nodes. How to create this. please help me. I am newer to java.
我想知道如何在 java 中创建自己的树,它由八个子节点组成,并且在每个子节点中它有许多子节点。如何创建这个。请帮我。我是java的新手。
回答by user3297129
A good design will be : Create a class RootNode with array of eight references to another class FirstLevelChildNode which in turn has dynamic array (say ArrayList) of another class ChildNodes, with required operations in each class...
一个好的设计是:创建一个 RootNode 类,其中包含对另一个类 FirstLevelChildNode 的八个引用的数组,该类又具有另一个类 ChildNodes 的动态数组(比如 ArrayList),每个类中都有所需的操作......
回答by therealrootuser
You'll probably need to create some sort of Node class to represent the nodes in the tree:
您可能需要创建某种 Node 类来表示树中的节点:
public class Node
{
private List<Node> children = null;
private String value;
public Node(String value)
{
this.children = new ArrayList<>();
this.value = value;
}
public void addChild(Node child)
{
children.add(child);
}
}
Then to populate your tree:
然后填充你的树:
public static void main(String [] args)
{
Node root = new Node("root");
root.addChild(new Node("child1"));
root.addChild(new Node("child2")); //etc.
}
You'll have to modify this to suit your own purposes, this code is just to give you an idea of the structure.
您必须修改它以适合您自己的目的,此代码只是为了让您了解结构。