是否可以在 Java 中创建对象树? [英] Is it possible to create a tree of objects in Java?

查看:26
本文介绍了是否可以在 Java 中创建对象树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 Java 创建一个对象树.我还想使用一个 Java 类,它可以轻松地从树中添加或删除节点.用于此目的的最佳类是什么?

I am trying to create a tree of Objects in Java. I also want to use a Java class that makes it easy to add or remove nodes from the tree. What would be the best class to use for this purpose?

示例:这是一个对象数组.数组顶部的对象是字符串world".这里的叶子是整数,我想添加字符串This is at (world, 0, 0)!"作为(world, 0, 0)"处的叶子.什么 Java 类最适合此目的?

Example: Here is an array of objects. The object at the top of the array is the string "world". The leaves are integers here, and I want to add the string "This is at (world, 0, 0)!" as a leaf at "(world, 0, 0)". What Java class would be best for this purpose?

"world"
  /\
 0  1
/ \  /\
0 1  0 1

推荐答案

制作您自己的.这很简单.超级超级简单:

Make your own. It's easy. Super super easy:

public class Tree{
    public Node root;
}

public class Node{
    public ArrayList<Node> children;
    public Node parent;
    public String value;
}

现在,将一个带有整数序列的字符串值放入如下方式:

Now, putting a string value with a sequence of integers would be done something like this:

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

获取值与此类似,只是您不会用给定值覆盖当前值.

Getting the value would be similar, except that you wouldn't overwrite the current value with a given value.

put 的英文描述:

  • 转到当前节点的第 nth 个子节点,其中 n 是路径中的下一个值.
  • 如果孩子不存在,创建它.
  • 重复直到到达路径的尽头.
  • 返回当前值(可选)
  • 将值设置为新值.
  • Go to the nth child of the current node, where n is the next value in your path.
  • If the child doesn't exist, create it.
  • Repeat until the end of the path is reached.
  • Return the current value (optional)
  • Set the value to the new value.

所以使用它看起来像这样:

So using this would look something like this:

Tree myTree = new Tree();
myTree.root = new Node();
int[] path = {0, 0, 0};
myTree.put("hi", path);
System.out.println(myTree.get(path));

你会在控制台中得到嗨".

And you'll get "hi" in your console.

这篇关于是否可以在 Java 中创建对象树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆