我最近一直在思考定义数组的两种方式之间的区别:
int[]数组 int[]数组
有区别吗?
我最近一直在思考定义数组的两种方式之间的区别:
int[]数组 int[]数组
有区别吗?
当前回答
这两个命令是一样的。
你可以使用语法来声明多个对象:
int[] arrayOne, arrayTwo; //both arrays
int arrayOne[], intOne; //one array one int
参见:http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html
其他回答
有一个细微的区别,如果你碰巧在同一个声明中声明了多个变量:
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。
但是int[] a将类型信息保存在一起,更详细,所以我更喜欢它。
两者同样有效。但是不鼓励使用int[]形式,根据编码约定,int[]形式是首选。请参阅官方Java数组教程:
类似地,你可以声明其他类型的数组: byte [] anArrayOfBytes; [] anArrayOfShorts短; 长[]anArrayOfLongs; [] anArrayOfFloats浮动; 双[]anArrayOfDoubles; 布尔[]anArrayOfBooleans; char [] anArrayOfChars; String [] anArrayOfStrings; 你也可以把方括号放在数组的名字后面: 浮动anArrayOfFloats [];//不鼓励使用此表单 然而,惯例不鼓励这种形式;括号标识数组类型,应该与类型名称一起出现。
注意最后一段。
我建议阅读官方的Sun/Oracle教程,而不是一些第三方的教程。否则,你可能最终会学到不好的做法。
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[] arrayOne, arrayTwo; //both arrays
int arrayOne[], intOne; //one array one int
参见:http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html