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
}
}
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 ofString[]
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 ofLinkedList<String>
and consequently aLinkedList<String>
cannot be used where aLinkedList<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
T[] localVar = (T[])(new Vector<T>(3).toArray()); // new T[3];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With