直接将数组初始值设定项传递给方法参数不起作用

Tin*_*iny 4 java arrays

package arraypkg;

import java.util.Arrays;

public class Main
{
    private static void foo(Object o[])
    {
        System.out.printf("%s", Arrays.toString(o));
    }

    public static void main(String[] args)
    {
       Object []o=new Object[]{1,2,3,4,5};
       foo(o);                     //Passing an array of objects to the foo() method.

       foo(new Object[]{6,7,8,9}); //This is valid as obvious.

       Object[] o1 = {1, 2};      //This is also fine.
       foo(o1);

       foo({1,2});               //This looks something similar to the preceding one. This is however wrong and doesn't compile - not a statement.
    }
}
Run Code Online (Sandbox Code Playgroud)

在前面的代码片段中,除最后一个之外的所有表达式都被编译并运行正常.虽然最后一个看起来类似于其立即语句的语句,但编译器发出编译时错误 - 非法启动表达式 - 而不是语句.为什么?

Roh*_*ain 8

foo({1,2});
Run Code Online (Sandbox Code Playgroud)

{1,2}这种数组初始化只能在你声明数组的地方工作..在其他地方,你必须使用new关键字来创建它.

这就是为什么: -

Object[] obj = {1, 2};
Run Code Online (Sandbox Code Playgroud)

很好..这是因为,reference我们在LHS上使用的类型暗示了数组的类型.但是,虽然我们在其他地方使用它,但是编译器无法找到类型(就像你的情况一样)..

尝试使用: -

  foo(new Object[]{1,2});
Run Code Online (Sandbox Code Playgroud)