[英]Why does Java allow both int x[] and int[] x?
NOTE: this question was previously marked as a duplicate. 注意:此问题以前被标记为重复。 It's subtly different, though: the other question asked what the difference is between the two syntaxes; 不过,它还是有细微的不同: 另一个问题是,两种语法之间有什么区别? whereas I know there's no difference in meaning, and I'm asking in that case why Java allows both. 而我知道含义没有区别,在这种情况下,我问的是Java为什么允许两者都允许。
Why does Java allow both Java为什么同时允许两者
int x[];
and 和
int[] x;
when I declare an array? 当我声明一个数组?
The latter makes much more sense: the variable is called x
, not x[]
, and its type is int[]
, not int
. 后者更有意义:该变量称为x
,而不是x[]
,其类型为int[]
,而不是int
。 Why not just enforce this? 为什么不仅仅执行这个呢? Allowing two different syntaxes seems just to invite confusion and inconsistency. 允许两种不同的语法似乎只是在引起混乱和不一致。 It even appears to make it possible to declare a two-dimensional array as 甚至似乎可以将二维数组声明为
int[] x[];
which is bordering on unreadable. 这几乎是不可读的。
Is it something borrowed from C? 是从C借来的吗? (Why would C do it that way round, anyway?) (无论如何,为什么C会那样做?)
It was added to help C programmers get used to Java. 它是为了帮助C程序员习惯Java而添加的。
In Java int[] x;
在Java中, int[] x;
is the preffered way. 是首选的方式。
At least from specification there is no explicit reason for the existence of both. 至少从规范上来说,没有明确的理由同时存在两者。 However as follows both ways provide a certain flexibility. 然而,以下两种方式都提供了一定的灵活性。 With one variable both declarations will provide you with an int array. 使用一个变量,两个声明都将为您提供一个int数组。
x and y are both arrays when: x和y都是以下情况的数组:
int[] x, y;
x is an array and y not when: x是数组,y不是数组,当:
int x[], y;
See also Oracle Java7 reference . 另请参见Oracle Java7参考 。 They also say that mixed notation is not recommended noting done the following example: 他们还说不建议使用混合表示法,并注意以下示例:
float[][] f[][], g[][][], h[]; // Yechh!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.