我最近一直在思考定义数组的两种方式之间的区别:

int[]数组 int[]数组

有区别吗?


当前回答

Java语言规范说:

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[][];

因此,它们将产生完全相同的字节代码。

其他回答

它们是一样的。其中一种(对某些人来说)比另一种更具可读性。

两者的意思是一样的。然而,这些变量的存在也允许:

int[] a, b[];

也就是:

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

然而,这是一种可怕的编码风格,不应该这样做。

在声明单个数组引用时,它们之间没有太大区别。所以下面两个声明是一样的。

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

当声明多个数组引用时,我们可以找到它们之间的区别。下面两句话的意思是一样的。事实上,这取决于程序员遵循哪一个。但是建议使用标准的Java表示法。

int a[],b[],c[]; // three array references
int[] a,b,c;  // three array references

它是从java所基于的C语言中借来的一种替代形式。

有趣的是,在java中有三种方法来定义一个有效的main方法:

public static void main(String[] args) public static void main(字符串args[]) public static void mainargs)

有一个细微的区别,如果你碰巧在同一个声明中声明了多个变量:

int[] a, b;  // Both a and b are arrays of type int
int c[], d;  // WARNING: c is an array, but d is just a regular int

注意,这是一种糟糕的编码风格,尽管编译器几乎肯定会在您尝试使用d时捕捉到您的错误。