Tree Implementation in Java We are implementing a Tree structure and came up with two possible Tree Implementations. Implementation-1 is a straight forward class while Implmentation-2 uses a nested Static Class.


  My Question to reviewers is what are the advantages/disadvantages of 
  each of the methods below and what is the preferable way ?


Tree Implementation -1

 public class TreeNode&lt;T&gt; implements Serializable, Iterable&lt;TreeNode&lt;T&gt;&gt; {
      private static final long serialVersionUID = 1L;

      private T name;
      private TreeNode&lt;T&gt; parent;
      private List&lt;TreeNode&lt;T&gt;&gt; children;



    public TreeNode(T data) {
        this.name = data;
        this.children = new ArrayList&lt;TreeNode&lt;T&gt;&gt;();
    }

    public TreeNode&lt;T&gt; addChild(T child) {
        TreeNode&lt;T&gt; childNode = new TreeNode&lt;T&gt;(child);
        childNode.parent = this;
        this.children.add(childNode);
        return childNode;
    }

 }


Tree Implementation-2: Here, we use a Static Nested Class

 public class Node {

    public static class TreeNode1&lt;T&gt;  implements Serializable {

            private static final long serialVersionUID = 1L;

            private String name;
            private TreeNode1&lt;T&gt; parent;
            private List&lt;TreeNode1&lt;T&gt;&gt; children;

            public TreeNode1(String name) {
                this.name = name;
            }

            public void addChild(TreeNode1&lt;T&gt; node) {
                if (children == null)
                    children = new ArrayList&lt;TreeNode1&lt;T&gt;&gt;();
                children.add(node);
                 node.parent = this;
            }


          }
    }
I don't see any reason for the added complexity of the second implementation. The Node class doesn't provide any methods or fields nor does it serve as a base class for your TreeNode1. It just makes naming the tree nodes worse: TreeNode is definitely a better name than Node.TreeNode1.

So in version 2 you end up with two classes:


The outer class Node does nothing useful.
The node class Node.TreeNode1 doesn't do anything a non-nested class couldn't do as well. 


Even if you embed the TreeNode1 class into a more functional outer class, there isn't much benefit from static nesting.

So I'd definitely prefer implementation 1.

A nested class can be a good solution in cases where access to the enclosing class is useful, but I'd hide it from the API user, e.g. by exposing a Node interface which is internally implemented by the nested class.