Cannot Instantiate Type in generics

半腔热情 提交于 2019-11-27 07:47:47

问题


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>

回答1:


While instantiating generics should be replaced with corresponding objects.

Ex:

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



回答2:


Wildcards ? cannot be used when creating new instances. You should change your code to something like that

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;

}


来源:https://stackoverflow.com/questions/12200136/cannot-instantiate-type-in-generics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!