I’m confused about the design and proper use of toArray(T[]) method in Set (and other collections). If I have a Set of String, why do I need to specify an array of String of size 0, if the method is going to allocate a new String array anyway?
Set<String> stringSet = new Set<String>();
// bla bla bla, insert Strings to set
String[] array = stringSet.toArray(new String[0]);
Is there a better way to just get the array without allocating extra arrays or the explicit type conversion?
The parameter is used to detect the type of the array that’s going to be created.
You could argue, why doesn’t the JVM use the generic type parameter of the stringSet to detect the type. The answer is that at runtime the generic type parameter is not known due to type erasure, i.e Set<String> becomes Set after compilation.
toArray(new Object[0]) is identical in function to toArray().
If the set 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 set.