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

int[]数组 int[]数组

有区别吗?


当前回答

它们在语义上是相同的。添加int array[]语法只是为了帮助C程序员适应java。

Int[]数组更可取,而且更容易混淆。

其他回答

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

int[] a, b[];

也就是:

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

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

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

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

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

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

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

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

两者之间没有任何区别;两者都声明一个int型数组。但是,前者是首选的,因为它将类型信息都保存在一个地方。后者只有在C/ c++程序员转向Java时才真正得到支持。