Reputation: 1260
In the Java collections framework, the Collection interface declares the following method:
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?
Upvotes: 21
Views: 20337
Reputation: 4884
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.
Upvotes: -1
Reputation: 597
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
Upvotes: 35
Reputation: 59378
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;
}
Upvotes: 20