使用函数返回的数组初始化多维数组

4

我对以下示例有问题:

public static void main(String[] args) {

    // this works
    int[] test1DArray = returnArray();

    int[][] test2DArray = new int[][] {

        // this does not work
        new int[]= returnArray(),

        // yet this does
        new int[] {1, 2 ,3}
}

private static int[] returnArray() {

    int[] a = {1, 2, 3};
    return a;
}

我正在寻找一种方法来创建一个二维数组,并使第二维度成为从方法返回的数组。我不明白为什么它不能工作,因为我在Eclipse中得到的错误是:

赋值语句左侧必须是一个变量

据我所知,我正在创建一个新的int数组,并将返回的值分配给它。像这样立即填充第二维数组:

new int[] {1, 2 ,3}

这个功能运行良好,我想用从returnArray()返回给我的数组做类似的事情。

非常感谢您的任何帮助。

p/

2个回答

4

只需使用:

int[][] test2DArray = new int[][] {
    returnArray(),
    new int[] {1,2 ,3}
};

谢谢,正是我想要的! - Schlachter Schmidt

2
尽管@Eran已经解决了这个问题,但我认为您应该了解为什么会出错。
当您初始化数组的内容时,实际上是向其中返回值。
例如:new int[]{1, 2, 3}test2Darray中返回1、2和3,而int[] n = new int[]{1, 2, 3} 是在test2Darray中初始化并声明一个数组。后者没有在数组中返回任何基本值,因此会出现错误。 returnValue()是一个方法,它确实返回一个值(整数数组)。因此,控制台将其视为输入new int[]{1, 2, 3}
因此,new int[]{1, 2, 3}returnValue() 都可以工作。

谢谢提供背景信息,这真的有助于我理解我哪里出错了! - Schlachter Schmidt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接