Representing Hierarchical Data in Java

by Amit


While working on odf4j, I faced an issue where I had to deal with a set of data which had a hierarchical relationship between them. Specifically, I could generate a tree to represent the relationship between them. The next obvious task was to implement the data structure.

A easy and simple, yet inelegant solution is to implement the tree using conventional C-style approach – instead of using structures, use Java classes.

However, a better approach is to use classes in the javax.swing.tree package. These classes are actually defined for use in jTree. However, with a little bit of manipulation, you can easily use them in your own projects. The additional benefit is that you also get some ready made methods like – depth first search, breadth first search, etc. This surely makes life easier!

The following code generates the tree structure shown earlier using the class javax.swing.tree.DefaultMutableTreeNode :


public class StyleTree {
private DefaultMutableTreeNode top;

public void getStyle(String style_name) {

//Create the nodes.
top = new DefaultMutableTreeNode("ODT Style Families");

createNodes(top);
search(style_name);
}

private void createNodes(DefaultMutableTreeNode top) {
DefaultMutableTreeNode style_family = null;
DefaultMutableTreeNode parent_style = null;
DefaultMutableTreeNode style_name_1 = null;
DefaultMutableTreeNode style_name_2 = null;
DefaultMutableTreeNode style_name_3 = null;

style_family = new DefaultMutableTreeNode("graphic");
top.add(style_family);

style_family = new DefaultMutableTreeNode("Paragraph");
top.add(style_family);

parent_style = new DefaultMutableTreeNode("standard");
style_family.add(parent_style);

style_name_1 = new DefaultMutableTreeNode("index");
parent_style.add(style_name_1);

style_name_2 = new DefaultMutableTreeNode("Text_20_body");
parent_style.add(style_name_2);

style_name_1 = new DefaultMutableTreeNode("P1");
style_name_2.add(style_name_1);

style_name_1 = new DefaultMutableTreeNode("P2");
style_name_2.add(style_name_1);

style_name_1 = new DefaultMutableTreeNode("Heading");
style_name_2.add(style_name_1);

style_name_1 = new DefaultMutableTreeNode("List");
style_name_2.add(style_name_1);

style_name_3 = new DefaultMutableTreeNode("caption");
parent_style.add(style_name_3);


style_family = new DefaultMutableTreeNode("table");
top.add(style_family);

style_family = new DefaultMutableTreeNode("table_row");
top.add(style_family);


}

private void search(String item){

.
.

}

}

}


I hope this is clear. In case of doubts, ping me back!

Advertisements