I have a tree of objects T, declared as
public class Tree<T> {
private Node<T> root;
public Tree(T rootData) {
root = new Node<T>();
root.data = rootData;
root.children = new ArrayList<Node<T>>();
}
public static class Node<T> {
private T data;
private Node<T> parent;
private List<Node<T>> children;
}
}
and want to add a function keepBranch, which reduces the tree to one of its branch.
But I need keepBranch to take an object T as a parameter, to select the branch.
Something like:
public void keepBranch(<T> param) {
for (Node<T> node : this.root.children) {
if (param.equals(node.data)) {
this.root = node;
}
}
}
Is there a way to do this? Or am I doing it wrong?
<T>is used to define a type variable in a certain context. But once defined, you can useTas you would use any other class name. (Syntactically, that is. You can't do everything you could do with a concrete class name.)public Tree(T rootData), so I wonder why you've thought that you need to use<T>.datain our code should be unique for whole tree. if it isn't so you can get wrong branch by data comparison.