开发者

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

开发者 https://www.devze.com 2023-02-03 08:37 出处:网络
One way to initialize a charsequence[] is charsequence[] item = {"abc", &qu开发者_StackOverflow社区ot;def"};

One way to initialize a charsequence[] is

charsequence[] item = {"abc", &qu开发者_StackOverflow社区ot;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?


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);
}


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

CharSequence[] ar = new String[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];
0

精彩评论

暂无评论...
验证码 换一张
取 消