23

How do I change something like this:

CharSequence cs[] = { "foo", "bar" };

to:

CharSequence cs[];

cs.add("foo"); // this is wrong...
cs.add("bar"); // this is wrong...
Che Jami
  • 5,151
  • 2
  • 21
  • 18
MarcoS
  • 17,323
  • 24
  • 96
  • 174

6 Answers6

92

Use a List object to manage items and when you have all the elements then convert to a CharSequence. Something like this:

List<String> listItems = new ArrayList<String>();

listItems.add("Item1");
listItems.add("Item2");
listItems.add("Item3");

final CharSequence[] charSequenceItems = listItems.toArray(new CharSequence[listItems.size()]);
Forest Katsch
  • 1,485
  • 2
  • 15
  • 26
David Guerrero
  • 1,080
  • 7
  • 7
6

You are almost there. You need to allocate space for the entries, which is automatically done for you in the initializing case above.

CharSequence cs[];

cs = new String[2];

cs[0] = "foo"; 
cs[1] = "bar"; 

Actually CharSequence is an Interface and can thus not directly be created, but String as one of its implementations can.

Pikaling
  • 8,282
  • 3
  • 27
  • 44
Heiko Rupp
  • 30,426
  • 13
  • 82
  • 119
2

You can also use List, to have a dynamic number of members in the array(list :)):

List<CharSequence>  cs = new ArrayList<CharSequence>();

cs.add("foo"); 
cs.add("bar"); 

If you want to use array, you can do:

CharSequence cs[];

cs = new String[2];

cs[0] = "foo"; 
cs[1] = "bar"; 
MByD
  • 135,866
  • 28
  • 264
  • 277
0

KOTLIN

First, convert the ArrayList to a regular, mutable list. Then, manually create the Array using the Array constructor. Make sure that your init function generates a data type that fits the Array (ex. don't put an int in a CharSequence arrray).

val exampleArray: ArrayList<String> arrayListOf("test1", "test2", "test3")
val exampleList = exampleArray.toList()
val exampleItems: Array<CharSequence?>? = exampleList?.size?.let { it1 -> Array(it1,{ i -> exampleArray?.get(i) }) }
Code on the Rocks
  • 11,488
  • 3
  • 53
  • 61
0

If you want it to be dynamical, you should think in an another structure and then convert it to a CharSequence when you need. Alternatively, that thread can be useful.

Community
  • 1
  • 1
Romain Piel
  • 11,017
  • 15
  • 71
  • 106
0

You could use ArrayList instead of raw arrays since need to add items dynamically.

Ron
  • 24,175
  • 8
  • 56
  • 97