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.