Generic tree implementation in Java

后端 未结 10 1239
甜味超标
甜味超标 2020-12-28 12:29

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.

相关标签:
10条回答
  • 2020-12-28 13:08

    I found an absolutely fantastic library http://jung.sourceforge.net, see the javadoc http://jung.sourceforge.net/doc/api/index.html . It is much more than just a graph implementation. With it you can visualize and layout graphs; plus, it has a bunch of standard graph algorithms you can use out of the box. Go, check it out! Although I ended up implementing my own basic graph (I didn't know of JUNG before), I use this library for visualization. It looks very neat!

    0 讨论(0)
  • 2020-12-28 13:08

    If you need an enterprise-level node tree, you could look into Java Content Repository (JCR). But it is far from the simple in-memory node tree solutions suggested here and more of a multi-user XML database with SQL and XPath.

    0 讨论(0)
  • 2020-12-28 13:10

    Ah, I was going to post a shameless plug to my solution and saw that someone already posted a link to it. Yeah, I had the same issue and I basically ended up writing my own Generic Tree. I've got tests for the tree node and the tree itself.

    I implemented the node as an object having a data field and a list of nodes (which are the children of that node).

    http://vivin.net/2010/01/30/generic-n-ary-tree-in-java/

    0 讨论(0)
  • 2020-12-28 13:15

    I use an XML DOM (XML describes a tree structure) and specifically the Open Source XOM (http://www.xom.nu). This is lightweight, nodes can be subclassed if required and very highly used and tested. It may be larger than you require but it has the advantage that any tree navigation methods (ancestors, siblings, etc.) are fully managed through XPath. You can also serialize the tree and transform it by tested XML methods. There is also a strong user community

    0 讨论(0)
  • 2020-12-28 13:16

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题