13

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.

4
  • 5
    Firstly, I suspect it predates generics. Secondly, I'm not sure what would happen for int.class etc. Commented Mar 17, 2016 at 7:12
  • @JonSkeet what do you mean when mentioning int.class? I thought that requesting class objects of primitives always returns their reference wrapper class object... Commented Mar 17, 2016 at 7:30
  • 2
    No, definitely not - if you call Array.newInstance(int.class, 5) you'll get an int[] back, not an Integer[]. Commented Mar 17, 2016 at 8:10
  • @JonSkeet Yes, now I see this. I didn't take arrays of primitives into consideration. Thank you. Commented Mar 17, 2016 at 16:06

1 Answer 1

13

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[]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.