一维数组引用多维数组

时间:2022-09-02 12:32:26

Why does this code compile?

为什么这段代码会编译?

int[] array = new int[][]{{1}}[0];

On the left side is one-dimensional array. On the right I thougth that three-dimensional, but it is not?

左侧是一维数组。在右边我认为那是三维的,但事实并非如此?

3 个解决方案

#1


7  

The right side is a one dimensional array that is the first (0th) element of the two-dimensional array

右侧是一维数组,它是二维数组的第一个(第0个)元素

new int[][]{{1}}

To show it out more clearly lets add parenthesis

为了更清楚地显示它,我们可以添加括号

int[] array = (new int[][]{{1}}) [0];// [0] is returning first row of 2D array
                          // which is 1D array so it can be assigned to `array` 

#2


3  

The right side expression does two things.

右侧表达式做了两件事。

//   instantiate new 2D array
//            ┌──────┸───────┑  ┌ access zeroth element of new 2D array
//            │              │  │
int[] array = new int[][]{{1}} [0];

This is basically equivalent to the following:

这基本上等同于以下内容:

int[][] array2D = new int[1][1];
array2D[0][0] = 1;

int[] array = array2D[0];

#3


0  

Two dimensional array is same as one dimensional array from memory management perspective ( meaning the data is stored in a single dimension). So, first element of two dimensional array is same as the first element of one dimensional array.

从存储器管理的角度来看,二维数组与一维数组相同(意味着数据存储在单个维度中)。因此,二维数组的第一个元素与一维数组的第一个元素相同。

#1


7  

The right side is a one dimensional array that is the first (0th) element of the two-dimensional array

右侧是一维数组,它是二维数组的第一个(第0个)元素

new int[][]{{1}}

To show it out more clearly lets add parenthesis

为了更清楚地显示它,我们可以添加括号

int[] array = (new int[][]{{1}}) [0];// [0] is returning first row of 2D array
                          // which is 1D array so it can be assigned to `array` 

#2


3  

The right side expression does two things.

右侧表达式做了两件事。

//   instantiate new 2D array
//            ┌──────┸───────┑  ┌ access zeroth element of new 2D array
//            │              │  │
int[] array = new int[][]{{1}} [0];

This is basically equivalent to the following:

这基本上等同于以下内容:

int[][] array2D = new int[1][1];
array2D[0][0] = 1;

int[] array = array2D[0];

#3


0  

Two dimensional array is same as one dimensional array from memory management perspective ( meaning the data is stored in a single dimension). So, first element of two dimensional array is same as the first element of one dimensional array.

从存储器管理的角度来看,二维数组与一维数组相同(意味着数据存储在单个维度中)。因此,二维数组的第一个元素与一维数组的第一个元素相同。