Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add data in charsequence [] dynamically in Java?

Tags:

java

android

One way to initialize a charsequence[] is

charsequence[] item = {"abc", "def"};

but I don't want to initialize it this way. Can someone please suggest some other way like the way we initialize string[] arrays?

like image 557
Akaash Garg Avatar asked Jan 06 '11 14:01

Akaash Garg


People also ask

How do you add to a CharSequence in Java?

The append(CharSequence, int, int) method of Writer Class in Java is used to append a specified portion of the specified charSequence on the writer. This charSequence is taken as a parameter. The starting index and ending index to be written are also taken as parameters.

Is CharSequence same as String?

Strings are CharSequences, so you can just use Strings and not worry. Android is merely trying to be helpful by allowing you to also specify other CharSequence objects, like StringBuffers.

Does String implement CharSequence?

String is a sequence of characters in Java. It is an immutable class and one of the most frequently used types in Java. This class implements the CharSequence, Serializable, and Comparable<String> interfaces.

What is CharSequence Java example?

For example: CharSequence obj = "hello"; String str = "hello"; System. out. println("output is : " + obj + " " + str);


2 Answers

This is the way you initialize a string array. You can also have:

CharSequence[] ar = new String[2];
like image 31
Bozho Avatar answered Sep 28 '22 04:09

Bozho


First, fix your variable declaration:

charsequence[] item;

is not valid syntax.
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:

List<CharSequence> charSequences = new ArrayList<>();
charSequences.add(new String("a"));
charSequences.add(new String("b"));
charSequences.add(new String("c"));
charSequences.add(new String("d"));
CharSequence[] charSequenceArray = charSequences.toArray(new
    CharSequence[charSequences.size()]);
for (CharSequence cs : charSequenceArray){
    System.out.println(cs);
}

The alternative is to instantiate a CharSequence[] with a finite length and use indexes to insert values. This would look something like

CharSequence[] item = new CharSequence[8]; //Creates a CharSequence[] of length 8
item[3] = "Hey Bro";//Puts "Hey Bro" at index 3 (the 4th element in the list as indexes are base 0
for (CharSequence cs : item){
    System.out.println(cs);
}
like image 160
Sandy Simonton Avatar answered Sep 28 '22 03:09

Sandy Simonton