我正在尝试用Java创建一个对象树.我还想使用一个Java类,它可以很容易地从树中添加或删除节点.什么是最好的课程用于此目的?
示例:这是一个对象数组.数组顶部的对象是字符串"world".叶子是整数,我想添加字符串"This is at at(world,0,0)!" 作为"(世界,0,0)"的叶子.什么Java类最适合此目的?
"world"
/\
0 1
/ \ /\
0 1 0 1
Run Code Online (Sandbox Code Playgroud)
小智 10
做你自己的.这很简单.超级超级容易:
public class Tree{
public Node root;
}
public class Node{
public ArrayList<Node> children;
public Node parent;
public String value;
}
Run Code Online (Sandbox Code Playgroud)
现在,使用整数序列放置一个字符串值将完成如下:
public class Tree{
public String put(String value, int[] path){
Node current = root;
for(int i=0;i<path.length;i++){
if(current.children.get(i)==null){
current.children.add(i, new Node());
}
current = current.children.get(i);
}
String ret = current.value;
current.value = value;
}
}
Run Code Online (Sandbox Code Playgroud)
获取值将类似,除非您不会使用给定值覆盖当前值.
put英文版的描述:
所以使用它看起来像这样:
Tree myTree = new Tree();
myTree.root = new Node();
int[] path = {0, 0, 0};
myTree.put("hi", path);
System.out.println(myTree.get(path));
Run Code Online (Sandbox Code Playgroud)
你会在你的控制台中得到"嗨".
| 归档时间: |
|
| 查看次数: |
14496 次 |
| 最近记录: |