Represent tree hierarchy in java [duplicate]

2019-04-02 18:44发布

Possible Duplicate:
Java tree data-structure?

I want to represent a hierarchical structure in java. The hierarchy can be of the form

Key
|
|-Value1
|  |-Value11
|    |-Value111
|-Value2
|  |-Value22
|-Value3
|-Value4

Can anyone suggest me the best possible data structure to represent this kind of hierarchy in java?

2条回答
乱世女痞
2楼-- · 2019-04-02 19:29

See this answer:

Java tree data-structure?

Basically, there is nothing in the standard libs that offers a Tree representation out of the box, except for the JTree in the swing package.

You can either roll your own (some tips offered in the linked answer), or use that one, which works well actually.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-04-02 19:45

Basically what you need is just an structure that will hold a few children and you model properties. You could represent this with a class structure like this:

public class TreeNode {

    private Collection<TreeNode> children;
    private String caption;

    public TreeNode(Collection<TreeNode> children, String caption) {
        super();
        this.children = children;
        this.caption = caption;
    }

    public Collection<TreeNode> getChildren() {
        return children;
    }

    public void setChildren(Collection<TreeNode> children) {
        this.children = children;
    }

    public String getCaption() {
        return caption;
    }

    public void setCaption(String caption) {
        this.caption = caption;
    }

}

You could take a look here, in order to take some ideas: Java tree data-structure?

查看更多
登录 后发表回答