79

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?

IAdapter
  • 62,595
  • 73
  • 179
  • 242
Laimoncijus
  • 8,615
  • 10
  • 58
  • 81

3 Answers3

256

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]
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
18

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()]);
seh
  • 14,999
  • 2
  • 48
  • 58
0

I know this post is 12 years old but I could not find a solution for this in Kotlin. Eventually I figured it out:

Kotlin:

val listOfStrings: List<String> = listOf("Hello,", "World!")
val charSequenceArray: Array<CharSequence> = listOfStrings.toArray(arrayOf<CharSequence>()) //Equivalent type to `CharSequence[]`
Da Mahdi03
  • 1,468
  • 1
  • 9
  • 18