我最近一直在思考定义数组的两种方式之间的区别:
int[]数组 int[]数组
有区别吗?
我最近一直在思考定义数组的两种方式之间的区别:
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[][];
因此,它们将产生完全相同的字节代码。
其他回答
没有区别。
引用孙杨的话:
[]可以作为类型的一部分出现在声明的开头,也可以作为特定变量的声明器的一部分出现,或者两者都有,如本例所示:byte[] rowvector, colvector, matrix[]; 此声明等价于: 字节行向量[],共向量[],矩阵[][];
两者之间没有任何区别;两者都声明一个int型数组。但是,前者是首选的,因为它将类型信息都保存在一个地方。后者只有在C/ c++程序员转向Java时才真正得到支持。
它们是一样的,但它们之间有一个重要的区别:
// 1.
int regular, array[];
// 2.
int[] regular, array;
在1。Regular只是一个int,而不是2。其中regular和array都是int类型的数组。
因此,你的第二种说法更可取,因为它更清楚。根据Oracle的本教程,第一种表单也不建议使用。
在声明单个数组引用时,它们之间没有太大区别。所以下面两个声明是一样的。
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[] 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时捕捉到您的错误。