I mean, is there any good reason for that? The method's got the following signature:
public static Object newInstance(Class<?> componentType,
int length)
throws NegativeArraySizeException
In my opinion, it would be much more convinient to declare the method as follows:
public static <T> T[] newInstance(Class<T> componentType, int length)
throws NegativeArraySizeException
That way, when creating an aray of generic type it would not be neccesary to perform additional casting, e.g.
public class Gen<T>{
private T[] a;
public static <T> Gen<T> createByClass(Class<T> clazz){
a = clazz.cast(Array.newIntance(clazz.getComponentType(), 8); //we have to invoke
//clazz.cast here.
}
}
Was there any good reason to declare the return value type as Object
? To me it seems very incovinient.
Arrays of generic types are not allowed because they're not sound. The problem is due to the interaction of Java arrays, which are not statically sound but are dynamically checked, with generics, which are statically sound and not dynamically checked.
If generic array creation were legal, then compiler generated casts would correct the program at compile time but it can fail at runtime, which violates the core fundamental system of generic types.
Java allows generic classes, methods, etc. that can be declared independent of types. However, Java does not allow the array to be generic. The reason for this is that in Java, arrays contain information related to their components and this information is used to allocate memory at runtime.
Array of generic typesNo, we cannot create an array of generic type objects if you try to do so, a compile time error is generated.
You can use Array.newInstance(Class<?> componentType, int length)
to create
Integer[] a = (Integer[])Array.newInstance(Integer.class, 5);
int[] b = (int[])Array.newInstance(int.class, 5);
int[][] c = (int[][])Array.newInstance(b.getClass(), 5);
The second example illustrates why this method cannot just return a generic array of objects, as arrays of primitves aren't array of objects (arrays of arrays, on the other hand, are).
Using this helper method...
private static <T> T[] newArray(Class<?> type, int len){
return (T[])Array.newInstance(type, len);
}
...with int[] b = newArray(int.class, 5);
will result in a compilation error:
Incompatible types, required int[], but found T[]
...and with int[] b = (int[])newArray(int.class, 5);
will result in a compilation error:
cannot cast Object[] to int[]
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