suter suter - 6 months ago 8
Java Question

How to convert Set<String> to String[]?

I need to get a

String[]
out of a
Set<String>
, but I don't know how to do it. The following fails:

Map<String, ?> myMap = gpxlist.getAll();
Set<String> myset = myMap.keySet();
String[] GPXFILES1 = (String[]) myset.toArray(); // Here it fails.


How can I fix it so that it works?

Answer

Use the Set#toArray(T[]) method taking a typed array argument of the same size.

String[] GPXFILES1 = myset.toArray(new String[myset.size()]);

A different size can also, but that would force the toArray() method to create a new array to return instead of reusing the provided argument, which may end up to be less efficient. See also the source code of AbstractCollection#toArray().

Comments