将数组作为Java中的方法参数传递

时间:2012-04-12 03:41:21

标签: java

以下代码在Java中使用简单的String数组。

package javaarray;

final public class Main
{
    public void someMethod(String[] str)
    {
        System.out.println(str[0]+"\t"+str[1]);
    }
    public static void main(String[] args)
    {
        String[] str1 = new String[] {"day", "night"};
        String[] str2 = {"black", "white"};

        //Both of the above statements are valid.

        Main main=new Main();
        main.someMethod(str1);
        main.someMethod(str2);

        //We can invoke the method someMethod by supplying both of the above arrays alternatively.

        main.someMethod(new String[] { "day", "night" }); //This is also valid as obvious.
        main.someMethod({ "black", "white" }); //This is however wrong. The compiler complains "Illegal start of expression not a statement" Why?
    }
}

在上面的代码片段中,我们可以像这样初始化数组。

String[] str1 = new String[] {"day", "night"};
String[] str2 = {"black", "white"};

我们可以直接将它传递给方法,而不是像这样分配。

main.someMethod(new String[] { "day", "night" });

如果是这样,那么以下陈述也应该有效。

main.someMethod({ "black", "white" });

但编译器抱怨“非法开始表达而不是声明”为什么?

1 个答案:

答案 0 :(得分:8)

根据Java语言规范(10.6. Array Initializers

  

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

因此,只有两种方法可以使用数组初始值设定项({"foo", "bar"}):

  1. 变量声明:String[] foo = {"foo", "bar"};
  2. 数组创建表达式:new String[] {"foo", "bar"};
  3. 您不能将数组初始值设定项用作方法参数。

    15.10. Array Creation Expressions

    ArrayCreationExpression:
        new PrimitiveType DimExprs Dimsopt
        new ClassOrInterfaceType DimExprs Dimsopt
        new PrimitiveType Dims ArrayInitializer 
        new ClassOrInterfaceType Dims ArrayInitializer