Var-Arg,多维数组

时间:2017-07-30 11:24:28

标签: java arrays variadic-functions

每当我将两个1-d数组作为参数传递给2-d var-arg方法时,它工作正常但如果我尝试将相同的两个1-d数组传递给具有简单2-d参数的方法它给了我错误 - The method m1(int[][]) in the type Asd is not applicable for the arguments (int[], int[])

根据我的知识int [] ... ==> int [] [],那么这种行为背后的原因是什么?

Var-Arg方法

public class Asd {


    public static void main(String[] args) {


        m1(new int[] {6,7},new int[] {8,9});

    }

    public static void m1(int[]... b)
    {

        System.out.println(b[0][0]);

    }
}

简单方法: -

public class Asd {


    public static void main(String[] args) {


        m1(new int[] {6,7},new int[] {8,9});

    }

    public static void m1(int[][] b)
    {

        System.out.println(b[0][0]);

    }
}

1 个答案:

答案 0 :(得分:0)

当多个参数传递给方法时,java编译器可能会将代码转换为作为给定类型的对象数组传递。

这就是当你尝试传递多个参数并且接收类型不是var-args的原因时,编译器会抱怨不同的数据类型。因为它们彼此不兼容。

您仍然可以通过创建二维数组来传递参数:

public static void main(String[] args) {
    m1( new int[][]{new int[]{6, 7}, new int[]{8, 9}} );
}

private static void m1(int[][] b) {
    System.out.println( b[0][0] );
}
相关问题