Necessity to allocate array for collection to array conversion in java using generics

Why is it necessary to allocate an array that can hold the values of a collection and pass it to the toArray(T []) method of this collection? I know there is the toArray() method that doesn't need the preallocated array, but this method returns Object[] which is absolutely bad. Also i would like to avoid type casting.

Example:

Set<String> strings = new HashSet<>();
// put some values in it
String[] stringArr = strings.toArray(/* preallocated array, why? */);

Assuming i use generics (everything else would be bad practice anyway), the used collection class should have enough information by itself to do this job for me. It could do something like this:

public someCollection<T> {
...
    public T[] toArray() {
        T[] arr = new T[this.length];
        // fill the array with the collection values
        return arr;
    }
}

Where is the catch, if i don't get it wrong this should be easy to implement in the default collection classes.

Jon Skeet
people
quotationmark

Why is it necessary to allocate an array that can hold the values of a collection and pass it to the toArray(T []) method of this collection?

It isn't. You can do so if you want to, but equally you can just pass in an empty array. Hence the documentation stating:

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.

You have to pass something in though, as the execution-time type of the array will be used to create another array of the same type if necessary. Using new T[...] will not create an array of the right execution-time type, due to type erasure. See the Java generics FAQ for more details, specifically the section on arrays of a concrete parameterized type.

people

See more on this question at Stackoverflow