Java – cannot instantiate a type in a generic

I have this course

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;

}

I'm trying to create a variable using this class

public static void main(String[] args){ 
        Tree<? super Number> num2 = new Tree<? super Number>(2);
    }

It gave me this mistake

Cannot instantiate the type Tree<? super Number>

Solution

Although instantiated generics should be replaced with corresponding objects

For example:

Tree<Integer> num2 = new Tree<Integer>(2);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>