Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
287 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...