Difference between int[] array and int array[]

2018-12-31 01:53发布

I have recently been thinking about the difference between the two ways of defining an array:

  1. int[] array
  2. int array[]

Is there a difference?

标签: java arrays
25条回答
墨雨无痕
2楼-- · 2018-12-31 02:18

From section 10.2 of the Java Language Specification:

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, as in this example:

 byte[] rowvector, colvector, matrix[];

This declaration is equivalent to:

byte rowvector[], colvector[], matrix[][];

Personally almost all the Java code I've ever seen uses the first form, which makes more sense by keeping all the type information about the variable in one place. I wish the second form were disallowed, to be honest... but such is life...

Fortunately I don't think I've ever seen this (valid) code:

String[] rectangular[] = new String[10][10];
查看更多
若你有天会懂
3楼-- · 2018-12-31 02:18

The most preferred option is int[] a - because int[] is the type, and a is the name. (your 2nd option is the same as this, with misplaced space)

Functionally there is no difference between them.

查看更多
后来的你喜欢了谁
4楼-- · 2018-12-31 02:21

They are semantically identical. The int array[] syntax was only added to help C programmers get used to java.

int[] array is much preferable, and less confusing.

查看更多
永恒的永恒
5楼-- · 2018-12-31 02:22

when declaring a single array reference, there is not much difference between them. so the following two declarations are same.

int a[];  // comfortable to programmers who migrated from C/C++
int[] a;  // standard java notation 

when declaring multiple array references, we can find difference between them. the following two statements mean same. in fact, it is up to the programmer which one is follow. but the standard java notation is recommended.

int a[],b[],c[]; // three array references
int[] a,b,c;  // three array references
查看更多
栀子花@的思念
6楼-- · 2018-12-31 02:25

As already stated, there's no much difference (if you declare only one variable per line).

Note that SonarQube treats your second case as a minor code smell:

Array designators "[]" should be on the type, not the variable (squid:S1197)

Array designators should always be located on the type for better code readability. Otherwise, developers must look both at the type and the variable name to know whether or not a variable is an array.

Noncompliant Code Example

int matrix[][];   // Noncompliant
int[] matrix[];   // Noncompliant

Compliant Solution

int[][] matrix;   // Compliant
查看更多
谁念西风独自凉
7楼-- · 2018-12-31 02:28

There is no difference.

I prefer the type[] name format at is is clear that the variable is an array (less looking around to find out what it is).

EDIT:

Oh wait there is a difference (I forgot because I never declare more than one variable at a time):

int[] foo, bar; // both are arrays
int foo[], bar; // foo is an array, bar is an int.
查看更多
登录 后发表回答