Passing directly an array initializer to a method parameter doesn't work

后端 未结 3 1243
悲&欢浪女
悲&欢浪女 2020-11-27 08:16
package arraypkg;

import java.util.Arrays;

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


        
3条回答
  •  借酒劲吻你
    2020-11-27 08:56

    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});
    

提交回复
热议问题