Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, how to populate a CharSequence array dynamically (not initializing?)

Tags:

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... 
like image 768
MarcoS Avatar asked Aug 15 '11 10:08

MarcoS


People also ask

How to initialize a dynamically allocated array to 0?

Initializing dynamically allocated arrays. It's easy to initialize a dynamic array to 0. Syntax: int *array{ new int[length]{} }; In the above syntax, the length denotes the number of elements to be added to the array. Since we need to initialize the array to 0, this should be left empty. We can initialize a dynamic array using an initializer ...

How do I insert values dynamically in a char sequence?

Typically, if you want to insert values dynamically, you would use a List<CharSequence>. If the object that you eventually need from the dynamic insertion is in fact a CharSequence [], convert the list to an array. Here's an example:

How to declare and populate an int array in Java?

Method 1: To declare the Java int array and then later populate and use it when required. int [] intArray1; //few lines of code here, for example to determine the size of array int size = 5; intArray1 = new int [size]; int j = 0; for (int i=0; i<size; i++) { intArray1 [i] = ++j; System.out.println (intArray1 [i]); }

What is charsequence in Java?

A CharSequence is a readable sequence of char values. This interface provides uniform, read-only access to many different kinds of char sequences. A char value represents a character in the Basic Multilingual Plane (BMP) or a surrogate.


2 Answers

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()]); 
like image 116
David Guerrero Avatar answered Oct 23 '22 23:10

David Guerrero


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.

like image 23
Heiko Rupp Avatar answered Oct 23 '22 22:10

Heiko Rupp