suter suter - 2 years ago 81
Java Question

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

I need to get a

out of a
, 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 Source

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().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download