无法理解数组声明int [] it2 = new int [] [] {{1}} [0];

时间:2014-05-18 11:06:52

标签: java arrays

请有人帮我理解这个数组的创建方式。

int[] it2= new int[][]it2[0];

{{1}}是一维数组,在右边我们有奇怪的初始化类型。 代码编译得很好,但我能够理解它是如何工作的。

1 个答案:

答案 0 :(得分:11)

将部分表达式分解以更好地理解它们:

int[] first = new int[]{1}; // create a new array with one element (the element is the number one)
int[][] second = new int[][]{first}; // create an array of the arrays. The only element of the outer array is the array created in the previous step.
int[] third = second[0]; // retrieve the first (and only) element of the array of array `second`. This is the same again as `first`.

现在我们将再次合并这些表达式。首先,我们合并firstsecond

int[][] second = new int[][]{new int[]{1}};
int[] third = second[0];

好的,没什么大不了的。但是,second表达式可以缩短。以下是等效的:

int[][] second = new int[][]int[] third = new int[][]{{1}}[0];
;
int[] third = second[0];

现在我们合并第二和第三。我们可以直接写:

{{1}}

我们有。