tags:

views:

227

answers:

4

I'm looking for any implementation of a pure Tree data structure for Java (that aren't graphical ones in java.awt), preferably generic.

With a generic tree I'd like to add elements that are not supposed to be sorted and do something like this:

TreeNode anotherNode = new TreeNode();
node.add(anotherNode);

…and then I'd like to traverse the nodes (so that I can save and preserve the structure in a file when I load the tree from the same file again).

Anyone knows what implementations exist or have any other idea to achieve this?

A: 

For a start, the TreeSet and TreeMap in the runtime are red-black-tree implementations.

Lucero
Yes, they use a tree internally, but they aren't tree themselves
David Pierre
Also, internally they use a binary tree implementation and so would not provide the "generic tree" functionality requested by the OP.
Adamski
+2  A: 

Scala has a nice Tree data structure. It's a "General Balanced Tree." It's not exactly Java, but it's close, and can serve as a good model.

It is hard to believe, given how much is in the base Java libraries, but there is no good generic Tree structure.

David Crawshaw
+3  A: 

You can use the DefaultMutableTreeNode defined in the javax.swing.tree package. It contains methods getUserObject() and setUserObject(Object) allowing you to attach data to each tree node. It allows an arbitrary number of child nodes for each parent and provides methods for iterating over the tree in a breadth-first or depth-first fashion (breadthFirstEnumeration() / depthFirstEnumeration()).

Also note that despite being resident in the javax.swing.tree package this class does not contain any UI code; It is merely the underlying model of JTree.

Adamski
A: 

Assuming you don't want to store arbitrary Java objects on the nodes, you could use the W3C DOM. It even comes with its own serialization format (I forget what it's called :-).

McDowell