我有这门课
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; }
我正在尝试使用此类创建一个变量
public static void main(String[] args){ Tree<? super Number> num2 = new Tree<? super Number>(2); }
它给了我这个错误
Cannot instantiate the type Tree<? super Number>
解决方法
虽然实例化泛型应该用相应的对象替换.
例如:
Tree<Integer> num2 = new Tree<Integer>(2);