Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array of Type Variables, in Java?

In Java it is possible to declare an array of type variables, but I'm not able to create the array. Is it impossible?

class ClassName<T> {
    {
        T[] localVar; // OK
        localVar = new T[3]; // Error: Cannot create a generic array of T
    }
}
like image 856
John Assymptoth Avatar asked Dec 22 '22 18:12

John Assymptoth


2 Answers

Generic type of array are not there in Java. You can go for ArrayList

Explanation :

array in java are of covariant type.

Java arrays have the property that there types are covariant , which means that an array of supertype references is a supertype of an array of subtype references.That is, Object[] is a supertype of String[] for example. As a result of covariance all the type rules apply that are customary for sub- and supertypes: a subtype array can be assigned to a supertype array variable, subtype arrays can be passed as arguments to methods that expect supertype arrays, and so on and so forth.Here is an example:

Object[] objArr = new String[10];// fine

In contrast, generic collections are not covariant. An instantiation of a parameterized type for a supertype is not considered a supertype of an instantiation of the same parameterized type for a subtype.That is, a LinkedList<Object> is not a super type of LinkedList<String> and consequently a LinkedList<String> cannot be used where a LinkedList<Object> is expected; there is no assignment compatibility between those two instantiations of the same parameterized type, etc.Here is an example that illustrates the difference:

LinkedList<Object> objLst = new LinkedList<String>(); // compile-time error

Source: http://www.angelikalanger.com/Articles/Papers/JavaGenerics/ArraysInJavaGenerics.htm

like image 190
jmj Avatar answered Jan 06 '23 18:01

jmj


T[] localVar = (T[])(new Vector<T>(3).toArray()); // new T[3];
like image 32
Wolfgang Avatar answered Jan 06 '23 20:01

Wolfgang