views:

4625

answers:

4

In the Java collections framework, the Collection interface declares the following method:

T[] toArray(T[] a)

"Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection."

If you wanted to implement this method, how would you create an array of the type of a, known only at runtime?

+3  A: 
Array.newInstance(Class componentType, int length)
Arno
+10  A: 

By looking at how ArrayList does it:

public <T> T[] toArray(T[] a) {
    if (a.length < size)
        a = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
    System.arraycopy(elementData, 0, a, 0, size);
    if (a.length > size)
        a[size] = null;
    return a;
}
SCdF
+7  A: 

Use the static method

java.lang.reflect.Array.newInstance(Class<?> componentType, int length)

A tutorial on its use can be found here: http://java.sun.com/docs/books/tutorial/reflect/special/arrayInstance.html

A: 

To create a new array of a generic type (which is only known at runtime), you have to create an array of Objects and simply cast it to the generic type and then use it as such. This is a limitation of the generics implementation of Java (erasure).

T[] newArray = (T[]) new Object[X]; // where X is the number of elements you want.

The function then takes the array given (a) and uses it (checking it's size beforehand) or creates a new one.

Christian P.