Is anyone aware of a generic tree (nodes may have multiple children) implementation for Java? It should come from a well trusted source and must be fully tested.
It just doesn't seem right implementing it myself. Almost reminds me of my university years when we were supposed to write all our collections ourselves.
EDIT: Found this project on java.net, might be worth looking into.
In Java, a tree node is implemented using a class. The data inside every node can be a string, char, integer, double, or float data type. A binary tree can be implemented in two ways: A node representation and an array representation.
Generic trees are a collection of nodes where each node is a data structure that consists of records and a list of references to its children(duplicate references are not allowed). Unlike the linked list, each node stores the address of multiple nodes.
A general tree is a tree where each node may have zero or more children (a binary tree is a specialized case of a general tree). General trees are used to model applications such as file systems.
Here it comes:
abstract class TreeNode implements Iterable<TreeNode> { private Set<TreeNode> children; public TreeNode() { children = new HashSet<TreeNode>(); } public boolean addChild(TreeNode n) { return children.add(n); } public boolean removeChild(TreeNode n) { return children.remove(n); } public Iterator<TreeNode> iterator() { return children.iterator(); } }
I am well trusted, but haven't tested the implementation.
There isn't a Tree class in the Collections libraries. However, there is one in the Swing Frameworks. DefaultTreeModel
I have used this in the past and it works well. It does pull in additional classes into your application though which may or may not be desirable.
You can also simulate a Tree using another collection and storing collections in it. Eg. List of Lists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With