[英]Java - How do I make a String array with values?
我知道如何创建一个空数组,但是如何从一开始就创建一个包含值的String
数组?
You could do something like this 你可以这样做
String[] myStrings = { "One", "Two", "Three" };
or in expression 或表达
functionCall(new String[] { "One", "Two", "Three" });
or 要么
String myStrings[];
myStrings = new String[] { "One", "Two", "Three" };
通过使用数组初始化列表语法,即:
String myArray[] = { "one", "two", "three" };
Another way to create an array with String apart from 使用String创建数组的另一种方法
String[] strings = { "abc", "def", "hij", "xyz" };
is to use split. 是用分裂。 I find this more readable if there are lots of Strings. 如果有很多字符串,我发现这更具可读性。
String[] strings = "abc,def,hij,xyz".split(",");
or the following is good if you are parsing lines of strings from another source. 或者,如果要解析来自其他源的字符串行,则以下内容很好。
String[] strings = ("abc\n" +
"def\n" +
"hij\n" +
"xyz").split("\n");
Another way is with Arrays.setAll
, or Arrays.fill
: 另一种方法是使用Arrays.setAll
或Arrays.fill
:
String[] v = new String[1000];
Arrays.setAll(v, i -> Integer.toString(i * 30));
//v => ["0", "30", "60", "90"... ]
Arrays.fill(v, "initial value");
//v => ["initial value", "initial value"... ]
This is more usefull for initializing (possibly large) arrays where you can compute each element from its index. 这对于初始化(可能很大)数组更有用,您可以从其索引中计算每个元素。
You want to initialize an array. 您想初始化一个数组。 (For more info - Tutoria l) (欲了解更多信息 - Tutoria l)
int []ar={11,22,33};
String []stringAr={"One","Two","Three"};
The []
may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both, as in this example: []
可能在声明开头作为类型的一部分出现,或作为特定变量的声明者的一部分出现,或者两者都出现,如下例所示:
byte[] rowvector, colvector, matrix[];
This declaration is equivalent to: 该声明相当于:
byte rowvector[], colvector[], matrix[][];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.