如何转换Set< String>到String []?
问题描述:
我需要从 Set< String>
中获取 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?
答
使用 设置#toArray(T [])
方法获取相同大小的类型数组参数。
Use the Set#toArray(T[])
method taking a typed array argument of the same size.
String[] GPXFILES1 = myset.toArray(new String[myset.size()]);
也可以使用不同的大小,但这会强制 toArray( )
创建一个新数组以返回而不是重用提供的参数的方法,这可能最终效率较低。
A different size can also be used, 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.