2017-06-05 85 views
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/

回答

4

只需使用:

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

谢谢,就是我在找的东西! –

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()工作。

+0

感谢您的背景,真的有助于了解我出错的地方! –