import Java.util.*;/** * A tree is a data strUCture that holds values of type V. * Each tree has a single value of type V and can have any number of * branches, each of which is itself a Tree. */public class Tree<V> { // The value of the tree is of type V. V value; // A Tree<V> can have branches, each of which is also a Tree<V> List<Tree<V>> branches = new ArrayList<Tree<V>>(); // Here's the constructor. Note the use of the type variable V. public Tree(V value) { this.value = value; } // These are instance methods for manipulating the node value and branches. // Note the use of the type variable V in the arguments or return types. V getValue() { return value; } void setValue(V value) { this.value = value; } int getNumBranches() { return branches.size(); } Tree<V> getBranch(int n) { return branches.get(n); } void addBranch(Tree<V> branch) { branches.add(branch); }}
import java.io.Serializable;import java.util.*;public class Tree<V extends Serializable & Comparable<V>> implements Serializable, Comparable<Tree<V>>{ V value; List<Tree<V>> branches = new ArrayList<Tree<V>>(); public Tree(V value) { this.value = value; } // Instance methods V getValue() { return value; } void setValue(V value) { this.value = value; } int getNumBranches() { return branches.size(); } Tree<V> getBranch(int n) { return branches.get(n); } void addBranch(Tree<V> branch) { branches.add(branch); } // This method is a nonrecursive implementation of Comparable<Tree<V>> // It only compares the value of this node and ignores branches. public int compareTo(Tree<V> that) { if (this.value == null && that.value == null) return 0; if (this.value == null) return -1; if (that.value == null) return 1; return this.value.compareTo(that.value); } // javac -Xlint warns us if we omit this field in a Serializable class PRivate static final long serialVersionUID = 833546143621133467L;}