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

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

问题描述

 包arraypkg;进口java.util.Arrays中;公共类主
{
    私有静态无效美孚(对象o [])
    {
        System.out.printf(%S,Arrays.toString(O));
    }    公共静态无效的主要(字串[] args)
    {
       [对象] 0 =新的对象[] {1,2,3,4,5};
       富(O); //传递对象的数组,把foo()方法。       富(新的对象[] {6,7,8,9}); //这是明显有效。       [对象] 01 = {1,2}; //这也很好。
       富(01);       富({1,2}); //这看起来类似于preceding 1东西。但是,这是错误的,不编译 - 不是一个声明。
    }
}

在preceding code段所有除了最后一个除权pressions编译并运行良好。虽然它看起来像它的直接陈述事情的最后声明中,编译器会发出一个编译时错误 - 前pression的非法启动 - 不是一个声明。为什么呢?


解决方案

 富({1,2});

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

这就是为什么: -

 对象[] = OBJ {1,2};

很好..
这是因为,阵列的类型,是由参考我们用LHS类型暗示。但是,当我们用它在其他地方,编译器不能找出类型(像你的情况)。

请尝试使用: -

 富(新对象[] {1,2});

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

That is why: -

Object[] obj = {1, 2};

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

Try using : -

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

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

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