ArrayList <String> in CharSequence []

What would be the easiest way to make CharSequence[] from an ArrayList<String> ?

Of course, I could iterate through each ArrayList element and copy to the CharSequence array, but maybe there is a better / faster way?

+56
java arraylist charsequence
Jun 13 '10 at 13:13
source share
2 answers

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

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

Here is a small 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] 
+206
Jun 13 '10 at 13:24
source share

Given that the String type already implements CharSequence , this conversion is as simple as asking the list to copy itself to a new array that will not actually copy any underlying character data. You simply copy references to String instances:

 final CharSequence[] chars = list.toArray(new CharSequence[list.size()]); 
+12
Jun 13 '10 at 13:29
source share



All Articles