问题描述:

int[] []x[];

I know that

int[] x;

int x[];

int []x;

and similar declares an array perfectly fine, but how does 3 sets for brackets, work exactly?

网友答案:

It is legal because Java Language Specification - 10.2. Array Variables allows it:

The array type of a variable depends on the bracket pairs that may appear as part of the type at the beginning of a variable declaration, or as part of the declarator for the variable, or both.

(emphasis mine)

So to put it simply int[] []x[]; is same as int[][][] x;.


Generally we should avoid mixed way of placing [] (or even placing [] after variable name). IMO it is because in Java we are used to declaring variables as

FullTypeDescription variableName 

instead of

SomeTypeInfo variable RestOfTypeInformation

and number of arrays dimensions is part of type information, so it should be separated.

Mixed type is allowed to let us write code like (to let C or C++ programmers migrate to Java easier):

int[][] a, b[];

instead of

int[][] a;
int[][][] b;

but still last way is preferred.

网友答案:

Although the follow 3 mean the same, the first one is the recommended one, since the type of x is an array of integers.

int[] x;   // Recommended
int x[];
int []x;

So, the other one should be:

int[][][] x;

Which is an array of array of array of integers.

Depending on how it is used, it can be thought of as a 3-dimensional array, e.g. see Fundamentals of Multidimensional Arrays

Of course, in reality, Java doesn't have multi-dimensional arrays. It is, as first stated, an array of array of array of integers, and each sub-array may have different lengths. But that is a longer topic.

网友答案:

Here's an example:

int[][] array = new int[1][2];

Above we have a double-dimensional array. Really, it's an array of arrays. So declaring it like so:

int[] array[] = new int[1][2];

You are still declaring an array of arrays, aka a double-dimensional array. this means that this:

int[] []array[] = new int[1][2][3];

Is the same as this:

int[][][] array = new int[1][2][3];

Because brackets after the array identifier ('array') were adapted for C programmers, they are treated as though they're located before the identifier.

Hope this helps! :)

相关阅读:
Top