Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot Instantiate Type in generics

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>
like image 327
KyelJmD Avatar asked Aug 30 '12 15:08

KyelJmD


People also ask

Can you instantiate objects using a type parameter?

Instantiating the type parameter Since the type parameter not class or, array, You cannot instantiate it. If you try to do so, a compile time error will be generated.

What is type erasure and why do we need it?

Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to: Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded.

Why are there no generic arrays in Java?

If generic array creation were legal, then compiler generated casts would correct the program at compile time but it can fail at runtime, which violates the core fundamental system of generic types.


2 Answers

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;

}
like image 183
Roman C Avatar answered Oct 16 '22 13:10

Roman C


While instantiating generics should be replaced with corresponding objects.

Ex:

 Tree<Integer> num2 = new Tree<Integer>(2);
like image 28
kosa Avatar answered Oct 16 '22 12:10

kosa