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
}
}
开发者_开发技巧
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];
This is only possible in a language with reified generics, like Gosu. Java has type erasure, so the type of T isn't available at runtime.
You can't. You can do it if you have the Class
object representing T
, you can use java.lang.reflect.Array
:
public static <T> T[] createArray(Class<T> clazz, int size) {
T[] array = (T[]) java.lang.reflect.Array.newInstance(clazz, length);
return array;
}
Another way that I got around this is by creating a different class to hold the type-Variable, then create an array of that class eg.
public class test<T>{
data[] localVar = new data[1];
private class data<E>{
E info;
public data(E e){ info = e; }
}
public void add(T e){ localVar[0] = new data<T>(e); }
}
the code above cant be used for anything practical unless you want to add one item to an array, but its just shows the idea.
You cannot initialize a generic type directly. However, you can create an array of Object type and cast it to generic array type as following:
class ClassName<T> {
{
T[] localVar = (T[]) new Object[3];
}
}
精彩评论