How do I initialize an object of type T (generic class parameter).
public class Bolsa<T> {
private int capacidad = 10;
private int elementosActual;
private T array;
public Bolsa(int capacidad) {
this.capacidad = capacidad;
array = new T[10];//Error en tiempo de compilación.
}
}
You can't do that in Java because of type erasure. You have these alternatives:
Pass the class of
T
as an argument in the constructor and create the array using reflection:The client code would call the constructor as follows:
Create an array of
Object
and do the respective cast when returning elements of the array (used in the implementation ofjava.util.ArrayList
):Use a device based on an array of
Object
:The first is the safest at development and runtime. The second and third have the trick of working with an array of objects and using a cast-down of the particular type that will be deleted at runtime, but supported during development-time work. Also, in the second and third options, you should be careful about exposing the array directly to clients as they might corrupt the information stored in it.
There are two problems with the code:
T
to which you want to assign the array of 10 objects of typeT
is not an array, therefore it will generate a compilation error as it cannot cast an array to an object...T
can beInteger
,Cow
,God
,Raccoon
or any other you define, but this never knows because itT
's actually a wild card for anyone). On the other hand, arrays DO need to know what type their elements are. Therefore this restriction is imposed.Because of this, at runtime you have to 'force' knowledge of the class type, for that you can use a class method
Array
callednewInstance
. This method receives two parameters: an object of type,Class
also generic, that allows the method to know at run time which class it refers to, and two, the size of the array. An example, trying to create an array of typeT
10 elements:where the variable
clase
is of typeClass<T>
. The expression(T[])
is used to cast the type of object returned by this method (which the Javadoc indicates is of type Object) to an array of typeT
, an expression that is safe because this array already knows, at run time, the class to the one it refers to.