0

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?

Community
  • 1
  • 1
user1368949
  • 198
  • 1
  • 1
  • 7
  • 4
    -1; seems you did not try anything. Entering 'java tree structure' on Google directly points to http://stackoverflow.com/questions/3522454/java-tree-data-structure – home Jun 26 '12 at 17:23

2 Answers2

7

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?

Community
  • 1
  • 1
Francisco Spaeth
  • 23,493
  • 7
  • 67
  • 106
6

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.

Community
  • 1
  • 1
pcalcao
  • 15,789
  • 1
  • 44
  • 64