参数列表中的 Java 数组初始化 [英] Java array initialization within argument list
问题描述
为什么在没有明确说明它是 String[] 的情况下,对 someMethod 的第一次调用无法编译?
How come the first call to someMethod doesn't compile without being explicit that it's String[]?
使用数组初始值设定项创建 String[] 数组很好,但不能使用它来传递参数.花括号是否以其他方式用于传递破坏我期望的行为方式的参数?
It's fine to use an array initializer to create a String[] array but you can't use it to pass an argument. Are the curly braces used in some other fashion for passing arguments that derails how I'd expect this to behave?
public void someMethod(String[] arr){
//do some magic
}
public void makeSomeMagic(){
String[] arr = {"cat", "fish", "cow"};
//Does not compile!
someMethod({"cat", "fish", "cow"});
//This compiles!
someMethod(new String[]{"cat", "fish", "cow"});
//This compiles!
someMethod(arr);
}
编译错误如下:
Moo 类型中的 someMethod(String[]) 方法不适用于参数 (String, String, String)
The method someMethod(String[]) in the type Moo is not applicable for the arguments (String, String, String)
推荐答案
您只能在声明数组变量或创建数组时使用 { "hello", "world" }
初始化符号表达式如 new String[] { ... }
.
You can only use the { "hello", "world" }
initialization notation when declaring an array variable or in an array creation expression such as new String[] { ... }
.
请参阅 第 10.6 节数组初始化器 在 Java 语言规范中:
See Section 10.6 Array Initializers in the Java Language Specification:
数组初始值设定项可以在声明中指定,或作为数组创建表达式(第 15.10 节)的一部分,创建数组并提供一些初始值
这篇关于参数列表中的 Java 数组初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!