简体   繁体   English

具有通用参数java的函数

[英]Function with generic parameter java

I have a tree of objects T , declared as 我有一棵对象T ,声明为

 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. 并想添加一个功能keepBranch ,将树减少到其分支之一。

But I need keepBranch to take an object T as a parameter , to select the branch. 但是我需要keepBranch对象T作为参数来选择分支。
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 . 将参数类型更改为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 : 进行更改,以便将节点的值与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 : 它应该是T param而不是<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 如评论中所述,它应该是param.equals(node.data)而不是node == param

Documentation : Lesson: Generics (Updated) 文档: 课程:泛型(已更新)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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