简体   繁体   中英

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 , wich 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?

Change the parameter type to T . But your comparison is wrong, you compare a value to a node. Change is so that the node's value is being compared to param :

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM