5

The following code uses simple arrays of String in Java.

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?
    }
}

In the above code snippet, we can initialize arrays like this.

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

and we can directly pass it to a method without being assigned like this.

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

If it is so, then the following statement should also be valid.

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

but the compiler complains "Illegal start of expression not a statement" Why?

4

1 回答 1

8

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

数组初始化器可以在声明中指定,或者作为数组创建表达式(§15.10)的一部分,创建一个数组并提供一些初始值:

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

  1. 变量声明:String[] foo = {"foo", "bar"};
  2. 数组创建表达式:new String[] {"foo", "bar"};

您不能将数组初始值设定项用作方法参数。

15.10。数组创建表达式

数组创建表达式:
    新的 PrimitiveType DimExprs Dimsopt
    新的 ClassOrInterfaceType DimExprs Dimsopt
    新的 PrimitiveType Dims ArrayInitializer
    新的 ClassOrInterfaceType Dims ArrayInitializer
于 2012-04-12T03:48:12.920 回答