将数组初始值设定项直接传递给方法参数不起作用 [英] Passing directly an array initializer to a method parameter doesn't work

查看:17
本文介绍了将数组初始值设定项直接传递给方法参数不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

在前面的代码片段中,除了最后一个表达式之外的所有表达式都被编译并运行良好.尽管最后一条语句看起来与它的直接语句类似,但编译器会发出编译时错误 - 表达式的非法开始 - 而不是语句.为什么?

In the preceding code snippet all the expressions except the last one are compiled and run fine. Although the last statement which looks something similar to its immediate statement, the compiler issues a compile-time error - illegal start of expression - not a statement. Why?

推荐答案

foo({1,2});

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

{1, 2} this kind of array initialization only work at the place you are declaring an array.. At other places, you have to create it using new keyword..

这就是为什么: -

Object[] obj = {1, 2};

还好..这是因为,数组的类型由我们在 LHS 上使用的 reference 类型隐含. 但是,当我们在其他地方使用它时,编译器无法找到类型(就像你的情况一样)..

Was fine.. This is because, the type of array, is implied by the type of reference we use on LHS.. But, while we use it somewhere else, Compiler cannot find out the type (Like in your case)..

尝试使用:-

  foo(new Object[]{1,2});

这篇关于将数组初始值设定项直接传递给方法参数不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆