I was just looking at the method defined in the List interface:
Returns an array containing all of the elements in this list in the correct order; the
My guess is that if you already know the concrete type of T
at the point you're calling toArray(T[])
, it's more performant to just declare an array of whatever it is than make the List
implementation call Arrays.newInstance()
for you -- plus in many cases you can re-use the array.
But if it annoys you, it's easy enough to write a utility method:
public static E[] ToArray(Collection c, Class componentType) {
E[] array = (E[]) Array.newInstance(componentType, c.size());
return c.toArray(array);
}
(Note that there's no way to write
, because there's no way to create an array of E
at runtime without a Class
object, and no way to get a Class
object for E
at runtime, because the generics have been erased.)