无法在泛型中实例化类型 [英] Cannot Instantiate Type in generics

查看:144
本文介绍了无法在泛型中实例化类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个课程

  public class Tree< T> {

//这棵树的分支列表
private List< Tree< super T>> branch = new ArrayList< Tree< super T>>();
public Tree(T t){this.t = t; }
public void addBranch(Tree<?super T> src){branch.add(src); }
公共树<?延伸T> getBranch(int branchNum){
return(Tree< ;? extends T>)branch.get(branchNum);
}


私人T t;

}

我试图从这个类中创建一个变量使用这个

  public static void main(String [] args){
Tree<超级号码> num2 =新树<?超级号码>(2);
}

它给了我这个错误

 无法实例化类型树<超级号码> 


解决方案

实例化泛型应该替换为相应的对象。 / p>

例如:

 树<整数> num2 = new Tree< Integer>(2); 


I have this class

public class Tree<T> {

    //List of branches for this tree
    private List<Tree<? super T>> branch = new ArrayList<Tree<? super T>>();
    public Tree(T t){ this.t = t; }
    public void addBranch(Tree< ? super T> src){ branch.add(src); }
    public Tree<? extends T> getBranch(int branchNum){
        return (Tree<? extends T>) branch.get(branchNum);
    }


    private T t;

}

And I am trying to create a variable out of this class using this

public static void main(String[] args){ 
        Tree<? super Number> num2 = new Tree<? super Number>(2);
    }

and it is giving me this error

Cannot instantiate the type Tree<? super Number>

解决方案

While instantiating generics should be replaced with corresponding objects.

Ex:

 Tree<Integer> num2 = new Tree<Integer>(2);

这篇关于无法在泛型中实例化类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆