ArrayList<String> to CharSequence[]

て烟熏妆下的殇ゞ 提交于 2019-12-18 10:58:14

问题


What would be the easiest way to make a CharSequence[] out of ArrayList<String>?

Sure I could iterate through every ArrayList item and copy to CharSequence array, but maybe there is better/faster way?


回答1:


You can use List#toArray(T[]) for this.

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]



回答2:


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:

final CharSequence[] chars = list.toArray(new CharSequence[list.size()]);


来源:https://stackoverflow.com/questions/3032342/arrayliststring-to-charsequence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!