Reputation: 121772
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?
Upvotes: 2
Views: 874
Reputation: 10577
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.
Upvotes: 2
Reputation: 108879
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 :-).
Upvotes: 0
Reputation: 54695
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
.
Upvotes: 3