1

I am trying to initialize Generic Parameter and Array

like

import java.util.ArrayList;
import java.util.List;

public class GenericExample<T> {

/*
 * Complier error -->
 * 
 * Cannot instantiate the type T
 */
private T t = new T();

/*
 * Complier error -->
 * 
 * Cannot create a generic array of T
 */
private T[] tArray = new T[10];

/*
 * No Complier error.
 */
private List<T> list = new ArrayList<T>();

}

There is no error when initialize list with Generic type as follows:

      /*
 * No Complier error.
 */
private List<T> list = new ArrayList<T>();

However, Complier errors appear when I am using the following initialization.

/*
 * Complier error -->
 * 
 * Cannot instantiate the type T
 */
private T t = new T();

        /*
 * Complier error -->
 * 
 * Cannot create a generic array of T
 */
private T[] tArray = new T[10];

Can someone help me out with the following 2 questions:

Q1: Why List<T> list = new ArrayList<T>(); does not encounter Complier error?

Q2: Why Complier error is thrown when using private T t = new T(); and private T[] tArray = new T[10]; ?

2 Answers 2

2

This is due to type erasure. The JVM has no idea what T is during runtime, since generic information is not retained for use during runtime (Java doesn't have reified generics). So when you have T t = new T(); and private T[] tArray = new T[10];, the JVM has no idea what T is.

List<T> list = new ArrayList<T>();

This works because you actually end up the following after compilation:

List list = new ArrayList();

Explicit casts to the appropriate type are then used when retrieving. That is, if you have:

List<String> list = new ArrayList<String>();
list.add("hello");
String hello = list.get(0);

During runtime what the JVM actually sees is:

List list = new ArrayList();
list.add("hello");
String hello = (String) list.get(0);
Sign up to request clarification or add additional context in comments.

Comments

0

In Java you cannot initialize a generic object if the generic has to be stored in memory (like in your first case and in the case of an object).

There are workarounds to this, you can cast your generics to the Object class. I can't remember how you do it in terms of syntax, but search for generic casting of arrays.

Comments

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.