ArrayList<String> to CharSequence[]

JavaArraylistCharsequence

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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]

Solution 2 - Java

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()]);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLaimoncijusView Question on Stackoverflow
Solution 1 - JavaBalusCView Answer on Stackoverflow
Solution 2 - JavasehView Answer on Stackoverflow