Java ArrayList<String> 到 CharSequence[]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3032342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ArrayList<String> to CharSequence[]
提问by Laimoncijus
What would be the easiest way to make a CharSequence[]
out of ArrayList<String>
?
最简单的方法CharSequence[]
是ArrayList<String>
什么?
Sure I could iterate through every ArrayList
item and copy to CharSequence
array, but maybe there is better/faster way?
当然我可以遍历每个ArrayList
项目并复制到CharSequence
数组,但也许有更好/更快的方法?
采纳答案by BalusC
You can use List#toArray(T[])
for this.
您可以List#toArray(T[])
为此使用。
CharSequence[] cs = list.toArray(new CharSequence[list.size()]);
Here's a little demo:
这是一个小演示:
List<String> list = Arrays.asList("foo", "bar", "waa");
CharSequence[] cs = list.toArray(new CharSequence[list.size()]);
System.out.println(Arrays.toString(cs)); // [foo, bar, waa]
回答by seh
Given that type String
already implements CharSequence
, this conversion is as simple as asking the list to copy itself into a fresh array, which won't actually copy any of the underlying character data. You're just copying references to String
instances around:
鉴于该类型String
已经实现了CharSequence
,这种转换就像要求列表将自身复制到一个新数组中一样简单,它实际上不会复制任何底层字符数据。您只是复制对String
周围实例的引用:
final CharSequence[] chars = list.toArray(new CharSequence[list.size()]);