简体   繁体   中英

Why do you need to specify an array to Set.toArray, which returns an array?

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, ie 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.

If you are using a collection, you may not know the exact number of entries that your set (or any other collection) will have. If you know from the beginning the number of entries, why don't you use an array instead of a collection?

The way I see it, the toArray() method is a simple way to create arrays using a collection for which you don't know a priori how many entries it will have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM