Cannot Instantiate Type in generics

后端 未结 2 674

I have this class

public class Tree {

    //List of branches for this tree
    private List> branch = new ArrayList<         


        
2条回答
  •  伪装坚强ぢ
    2020-12-11 18:41

    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 num2 = new Tree(2);
        num2.addBranch(new Tree(1));
        Tree num3 = (Tree) num2.getBranch(0);
        System.out.println(num3);
      }
    }
    
    class Tree {
    
      //List of branches for this tree
      private List> branch = new ArrayList>();
      public Tree(T t){ this.t = t; }
      public void addBranch(Tree src){ branch.add((Tree) src); }
      public Tree getBranch(int branchNum){
        return (Tree) branch.get(branchNum);
      }
    
      public String toString(){
        return String.valueOf(t);
      }
    
      private T t;
    
    }
    

提交回复
热议问题