Java 中的数组声明和初始化。数组的行为不同,当它们的下标索引的位置在它们的声明中改变时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16752689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:52:59  来源:igfitidea点击:

Array declaration and initialization in Java. Arrays behave differently, when the position of their subscript indices is changed in their declaration

javaarrays

提问by Tiny

The following is the obvious and usual array declaration and initialization in Java.

以下是 Java 中明显且常用的数组声明和初始化。

int r[], s[];       //<-------
r=new int[10];
s=new int[10];

A very similar case behaves differently, when the position of []is changed in the declaration statement like as shown below.

[]声明语句中的位置改变时,非常相似的情况表现不同,如下所示。

int []p, q[];       //<-------
p=new int[10];
q=new int[10][10];

Please look at the declaration. The position of []has been changed from r[]to []p. In this case, the array qbehaves like an array of arrays of type int(which is completely different from the previous case).

请看声明。的位置[]已从 更改r[][]p。在这种情况下,数组的q行为类似于类型数组的数组int(这与前一种情况完全不同)。

The question:Why is q, in this declaration int []p, q[];treated as a two dimensional array?

问题:为什么q, 在这个声明中int []p, q[];被视为二维数组?



Additional information:

附加信息:

The following syntax looks wonky.

以下语法看起来很奇怪。

int []a[];

This however, complies fine and just behaves like int a[][];or int [][]a;.

然而,这很好,只是表现得像int a[][];or int [][]a;

Hence, the following cases are all valid.

因此,以下情况均有效。

int [][]e[][][];
int [][][][][]f[][][][];

回答by zw324

Look at JLS on Arrays:

看看数组上的JLS

The []may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both.

[]可能显示为在声明的开头所述类型的部分,或作为说明符用于特定变量,或两者的一部分。

and

Brackets are allowed in declarators as a nod to the tradition of C and C++. The general rules for variable declaration, however, permit brackets to appear on both the type and in declarators, so that the local variable declaration:

float[][] f[][], g[][][], h[];  // Yechh!

is equivalent to the series of declarations:

float[][][][] f;
float[][][][][] g;
float[][][] h;

声明符中允许使用方括号作为对 C 和 C++ 传统的认可。然而,变量声明的一般规则允许括号出现在类型和声明符中,以便局部变量声明:

float[][] f[][], g[][][], h[];  // Yechh!

相当于一系列的声明:

float[][][][] f;
float[][][][][] g;
float[][][] h;

So for example:

例如:

int []p, q[];

is just

只是

int[] p, q[]

which is in fact

这实际上是

int p[]; int q[][]

The rest are all similar.

其余的都差不多。

回答by ZhongYu

The sane way of declaring a variable is

声明变量的明智方法是

type name

So if type is int[], we should write

所以如果类型是int[],我们应该写

int[] array

Never write

从不写

int array[]

it is gibberish (though it's legal)

这是胡言乱语(虽然它是合法的)