初始化charsequence []的一种方法是
charsequence[] item = {"abc","def"};
但我不想以这种方式初始化它。有人可以建议其他方式,如我们初始化string []数组的方式......
感谢
答案 0 :(得分:6)
首先修复你的变量声明:
charsequence[] item
语法无效。
通常,如果要动态插入值,则使用List。如果动态插入最终需要的对象实际上是CharSequence [],则将列表转换为数组。这是一个例子:
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);
}
另一种方法是使用有限长度实例化CharSequence []并使用索引插入值。这看起来像是:
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);
}
答案 1 :(得分:5)
这是初始化字符串数组的方式。你也可以:
CharSequence[] ar = new String[2];
答案 2 :(得分:0)
CharSequence是您无法初始化的界面,如new CharSequence[]{....}
使用它的实现
初始化它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
和他们的数组
CharSequence[] c = new String[2];
CharSequence[] c = new StringBuffer[2];
CharSequence[] c = new StringBuilder[2];