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

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;  // 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时捕捉到您的错误。

是的,有区别。

Int [] a = new Int [100];// 'a'本身不是数组,数组存储为地址 在内存的其他地方,'a'只保存该地址

Int b[] = new Int [100];//当创建像cleary这样的数组时,显示'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

两者同样有效。但是不鼓励使用int[]形式,根据编码约定,int[]形式是首选。请参阅官方Java数组教程:

类似地,你可以声明其他类型的数组: byte [] anArrayOfBytes; [] anArrayOfShorts短; 长[]anArrayOfLongs; [] anArrayOfFloats浮动; 双[]anArrayOfDoubles; 布尔[]anArrayOfBooleans; char [] anArrayOfChars; String [] anArrayOfStrings; 你也可以把方括号放在数组的名字后面: 浮动anArrayOfFloats [];//不鼓励使用此表单 然而,惯例不鼓励这种形式;括号标识数组类型,应该与类型名称一起出现。

注意最后一段。

我建议阅读官方的Sun/Oracle教程,而不是一些第三方的教程。否则,你可能最终会学到不好的做法。

在Java中,这只是说同一件事的不同语法方法。