4

I've learned following two methods for creating generic arrays.

One is

@SuppressWarnings("unchecked")
static <T> T[] array1(final Class<T> elementType, final int size) {

    return (T[]) Array.newInstance(elementType, size);
}

And the other is

static <T> T[] array2(final Class<T[]> arrayType, final int size) {

    return arrayType.cast(Array.newInstance(arrayType.getComponentType(), size));
}

Which is better? Are they same (internally)? Is any case actually wrong?

3
  • I think the first approach is better Commented Jun 20, 2013 at 3:30
  • can someone explain the second approach? what is it doing? Commented Jun 20, 2013 at 5:51
  • Following Question stackoverflow.com/questions/17226379/… Commented Jun 21, 2013 at 1:30

3 Answers 3

6

Behind the scenes, the two do effectively the same thing, except that in option 1 you're passing in T's class object and in option 2 you're passing in T[]'s class object.

I prefer option 1 because it's shorter and easier to read. Then again, it's the same as Array.newInstance with a cast added, so I'm not sure that your method adds a lot of value. :-)

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

Comments

2

Note that the first one is not type-safe. For example, the following causes a ClassCastException:

array1(int.class, 5);

3 Comments

Checked and confirmed. Both methods don't event compile for primitive types.
@JinKwon: No, the first one compiles and throws an exception. The second one doesn't compile, and is type-safe.
doesn't compile if assigned to an int[] variable
0

Another (better) way to create generic arrays

@SafeVarargs
static <E> E[] newArray(int length, E... array)
{
    return Arrays.copyOf(array, length);
}


Integer[] ints = newArray(10);

String[] strings = newArray(10); 

3 Comments

Note that this will fail if the caller itself is in generic scope and doesn't resolve T to a concrete type.
only because of erasure:) and the same problem exists for array1/array2() too.
It doesn't because they use a Class type token and reflection to work around erasure.

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.