9

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?

Dada
  • 6,313
  • 7
  • 24
  • 43
Akaash Garg
  • 145
  • 1
  • 2
  • 8
  • 1
    You should probably give an example of the preferred way because you can initialize a string array the same way as you posted. – Shaded Jan 06 '11 at 14:03
  • Similarly, utilizing modern Java, you may want an unmodifiable list: `List.of( "abc" , "def" )`. – Basil Bourque Dec 19 '21 at 06:16

3 Answers3

11

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);
}
Dada
  • 6,313
  • 7
  • 24
  • 43
Sandy Simonton
  • 604
  • 5
  • 15
5

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

CharSequence[] ar = new String[2];
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
2

CharSequence is an interface you can't initialize like new CharSequence[]{....}

Initialize it with it's implementations:

CharSequence c = new String("s");
System.out.println(c) // s

CharSequence c = new StringBuffer("s");
System.out.println(c) // s

CharSequence c = new StringBuilder("s");
System.out.println(c); // s
 

and their's arrays

CharSequence[] c = new String[2];
c = new StringBuffer[2];
c = new StringBuilder[2];
Sae1962
  • 1,122
  • 15
  • 31