9
public class Sample<T>{

 T data;

   Sample(){

     data = ????;

  }

}

How can i assign a default value to data ?

1

2 Answers 2

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;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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()

1 Comment

"You can't." ... unless the default value is null. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.