不能实例化泛型类型(Cannot Instantiate Type in generics)

2019-06-27 14:01发布

我有这个类

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>

Answer 1:

虽然泛型实例应与相应的对象来代替。

例如:

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


Answer 2:

通配符? 创建新实例时,不能使用。 您应该更改您的代码类似的东西

import java.util.ArrayList;
import java.util.List;

public class Test1 {
  public static void main(String[] args){
    Tree<? super Number> num2 = new Tree<Number>(2);
    num2.addBranch(new Tree<Number>(1));
    Tree<? super Number> num3 = (Tree<? super Number>) num2.getBranch(0);
    System.out.println(num3);
  }
}

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<Number> src){ branch.add((Tree<? super T>) src); }
  public Tree<? extends T> getBranch(int branchNum){
    return (Tree<? extends T>) branch.get(branchNum);
  }

  public String toString(){
    return String.valueOf(t);
  }

  private T t;

}


文章来源: Cannot Instantiate Type in generics