Ale*_*man 125
你可以这样做
String[] myStrings = { "One", "Two", "Three" };
Run Code Online (Sandbox Code Playgroud)
或表达
functionCall(new String[] { "One", "Two", "Three" });
Run Code Online (Sandbox Code Playgroud)
要么
String myStrings[];
myStrings = new String[] { "One", "Two", "Three" };
Run Code Online (Sandbox Code Playgroud)
通过使用数组初始化列表语法,即:
String myArray[] = { "one", "two", "three" };
Run Code Online (Sandbox Code Playgroud)
使用 String 创建数组的另一种方法除了
String[] strings = { "abc", "def", "hij", "xyz" };
Run Code Online (Sandbox Code Playgroud)
就是用split。我发现如果有很多字符串,这更具可读性。
String[] strings = "abc,def,hij,xyz".split(",");
Run Code Online (Sandbox Code Playgroud)
或者如果您要解析来自其他来源的字符串行,则以下内容很好。
String[] strings = ("abc\n" +
"def\n" +
"hij\n" +
"xyz").split("\n");
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用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"... ]
Run Code Online (Sandbox Code Playgroud)
这对于初始化(可能很大)数组更有用,您可以从索引计算每个元素。