tags:

views:

101

answers:

2
public class Sample<T>{

 T data;

   Sample(){

     data = ????;

  }

}

How can i assign a default value to data ?

+4  A: 

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
*"You can't."* ... unless the default value is `null`. :-)
Stephen C
yes, that's the obvious one :)
Bozho
+5  A: 

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;
  }
}
John C