如何转换Set< String>到String []? [英] How to convert Set<String> to String[]?

查看:110
本文介绍了如何转换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.

另请参阅源代码 AbstractCollection#toArray()

这篇关于如何转换Set&lt; String&gt;到String []?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆