Search code examples
javagenerics

Function with generic parameter java


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?


Solution

  • It should be T param instead of <T> param :

    public void keepBranch(T param) {
    
            for (Node<T> node : this.root.children) {
                if (param.equals(node.data)) {
                    this.root = node;
                }
            }
    }
    

    EDIT

    As said in comments, it should be param.equals(node.data) instead of node == param

    Documentation : Lesson: Generics (Updated)