9
public class Sample<T>{

 T data;

   Sample(){

     data = ????;

  }

}

How can i assign a default value to data ?

Jeroen Rosenberg
  • 4,552
  • 3
  • 27
  • 39
Ravit Teja
  • 301
  • 6
  • 12
  • Duplicate of : http://stackoverflow.com/questions/182636/how-to-determine-the-class-of-a-generic-type – Nicolas Oct 18 '10 at 08:35

2 Answers2

8

Bozho is right (you can't). If you definitely want it to start off with a value, make that value an argument to the constructor. For instance:

public class Sample<T> {
  T data;
  Sample(T data) {
     this.data = data;
  }
}
johncip
  • 2,087
  • 18
  • 24
7

You can't. The type T is erased at runtime, so you can't instantiate it.

If you pass a Class argument to the Sample(..) constructor, you can call clazz.newInstance()

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140