Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic tree implementation in Java

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.

like image 653
Ivan Koblik Avatar asked Aug 31 '09 08:08

Ivan Koblik


People also ask

Is there a tree implementation in Java?

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.

What is a generic tree?

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.

What is a general tree?

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.


2 Answers

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.

like image 136
Zed Avatar answered Oct 02 '22 06:10

Zed


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.

like image 20
Fortyrunner Avatar answered Oct 02 '22 05:10

Fortyrunner