St.Antario
St.Antario

Reputation: 27435

Why isn't Array.newInstance(Class<?>, int) generic?

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.

Upvotes: 13

Views: 1650

Answers (1)

Peter Walser
Peter Walser

Reputation: 15706

You can use Array.newInstance(Class<?> componentType, int length) to create

  • Arrays of Objects: Integer[] a = (Integer[])Array.newInstance(Integer.class, 5);
  • Arrays of primitives: int[] b = (int[])Array.newInstance(int.class, 5);
  • Arrays of Arrays: 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[]

Upvotes: 13

Related Questions