21

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

<T> 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?

Community
  • 1
  • 1
Sam
  • 1,260
  • 2
  • 11
  • 32

4 Answers4

35

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

user9116
  • 597
  • 3
  • 7
20

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
  • 57,260
  • 24
  • 77
  • 113
3
Array.newInstance(Class componentType, int length)
Arno
  • 2,169
  • 1
  • 15
  • 12
-1

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.
  • 4,784
  • 7
  • 53
  • 70
  • 3
    Unlike all other answers here, this way does *not* create an array of T. Because of erasure you can assign it to a T[], but you won't always get away with it. If in a specific instance T is String, and the array you created there is (returned to another method and) assigned to String[] (which won't require a cast), you'll get an unexpected ClassCastException. This is an example of type pollution. Don't do it! – Wouter Coekaerts Apr 11 '11 at 15:05