参数列表中的 Java 数组初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4443892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 17:34:51  来源:igfitidea点击:

Java array initialization within argument list

javaarrays

提问by Nick Swarr

How come the first call to someMethod doesn't compile without being explicit that it's String[]?

为什么在没有明确说明它是 String[] 的情况下,对 someMethod 的第一次调用不能编译?

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?

可以使用数组初始值设定项创建 String[] 数组,但不能使用它来传递参数。花括号是否以其他方式用于传递使我期望这种行为脱轨的参数?

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

The compiler error is the following:

编译器错误如下:

The method someMethod(String[]) in the type Moo is not applicable for the arguments (String, String, String)

Moo 类型中的 someMethod(String[]) 方法不适用于参数 (String, String, String)

采纳答案by aioobe

You can only use the { "hello", "world" }initialization notation when declaring an array variable or in an array creation expression such as new String[] { ... }.

您只能{ "hello", "world" }在声明数组变量时或在数组创建表达式(如new String[] { ... }.

See Section 10.6 Array Initializersin the Java Language Specification:

请参阅Java 语言规范中的第 10.6 节数组初始值设定项

An array initializer may be specified in a declaration, or as part of an array creation expression (§15.10), creating an array and providing some initial values

数组初始值设定项可以在声明中指定,或作为数组创建表达式(第 15.10 节)的一部分,创建数组并提供一些初始值

回答by 0x2D9A3

If you don't want to use explicit String[], use:

如果您不想使用显式String[],请使用:

public void someMethod(String... arr){
    //do some magic
}
…
someMethod("cm", "applicant", "lead");


The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments.

最后一个参数类型后的三个句点表示最后一个参数可以作为数组或参数序列传递。

Read more.

阅读更多

回答by Goran Jovic

Or you can use varargs:

或者你可以使用可变参数:

public void someMethod(String... arr){
    //do some magic
}

public void makeSomeMagic(){
    someMethod("cat", "fish", "cow");
}

It's basically a fancy syntax for an array parameter (vararg must be the last parameter in method signature).

它基本上是数组参数的奇特语法(vararg 必须是方法签名中的最后一个参数)。

回答by Ralph

You can use the curly braces to initialize an array. In every else case it is used to define blocks of statments.

您可以使用花括号初始化数组。在其他情况下,它用于定义语句块。