简体   繁体   English

java多维数组符号

[英]java multidimensional array notation

To create an length 5 int array, we use the syntax: 要创建一个长度为5的int数组,我们使用以下语法:

 int[] x = new int[5]

To create a 2 dimensional array, an array of int arrays, we say: 要创建二维数组,即int数组的数组,我们说:

 int[][] x = new int[5][];

This creates an array of length 5, which can hold int[] objects. 这将创建一个长度为5的数组,该数组可以容纳int []个对象。

For this second case, why isn't the syntax this: ? 对于第二种情况,为什么语法不是:

int[][] x = new int[][5]

After all, 5 defines how many int arrays we can have. 毕竟5定义了我们可以拥有多少个int数组。 Not the size of the int arrays that we're going to put into x. 不是我们要放入x中的int数组的大小。

The array bring declared is the first dimension, so declaring the referenced array size does nothing to allocate the actual array. 带声明的数组是第一个维度,因此,声明引用的数组大小并不会分配实际的数组。 It would be similar to coding this: 这类似于编码:

int[] a = new int[];

It would be really weird to have the indices for lookups be different from the indices for construction . 查找索引与构造索引不同真的很奇怪。 So if you had int[][] x= new int[][5] , then you'd look up the elements with x[0..4][foo] , which is just more confusing than the alternative. 因此,如果您有int[][] x= new int[][5] ,那么您将使用x[0..4][foo]查找元素,这比替代方法更容易混淆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM