From an interface-perspective, I agree.
The method only needs the type (apart from the side-effects), so it would be appropriate to only demand the type.
The main reason is efficiency, I guess. The implementation that only takes the type is significantly slower, I did not check the implementation details though (see the benchmarks in .toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])? and the blog Arrays of Wisdom of the Ancients).
However, note that we got a new variant since Java 11 which comes closer to what you want and is also more appropriate in this situation:
toArray(Foo[]::new)
From its documentation:
Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.
Use toArray()
to create an array whose runtime type is Object[]
, or use toArray(T[])
to reuse an existing array.
The default implementation calls the generator function with zero and then passes the resulting array to toArray(T[])
.
The method does not need reflection since you provide the generator directly.
To summarize, nowadays you should use
toArray()
if you want Object[]
(rarely appropriate),
toArray(T[])
if you want to reuse an existing array (should be large enough),
toArray(IntFunction<T[]>)
if you want type safety and a new array.
toArray
and, if the list will fit in it, it will be used. (If not, a new one is created.) So...? – RolonType[].class
ornew Type[0]
, a new object would need to be instantiated either way. The former would require reflection. – FellmongertoArray
will create a new array for you anyway if the given array is too small, it is already using reflection, and when you pass innew Type[0]
, you're actually creating 2 arrays, since the zero-length array will be discarded, so passing inType[].class
would actually be more efficient. – WaiterArray.newInstance
will be called (based on the last implementation I've seen of it). – Fellmonger