Java中两个数组声明之间的区别是什么?

在我的书中,他们一直在以下两种方法之间切换声明数组的方式:

int array1[] = {1, 2, 3}; int[] array2 = {1, 2, 3}; 

我想知道两个括号的位置之间有什么区别,为什么当我把括号放在名字后面(例如在数组1中)时,为什么我必须将它初始化为一组值或一个新的数组,但在array2中,我可以简单地说“int [] array2;” 然后再用它……?

它们是相同的,除非你提到你必须初始化它,如果你把括号放在名称后面。 在名称之前声明它们的一个优点是多个数组初始化,如下所示:

 int [] myArray1, myArray2; int myArray1[], myArray2[]; 

根据文档的Java方法是将括号放在数组名称之前。

它们之间没有区别,因为它们都声明了一个“int of int”类型的变量。 没有“Java方式”(但首选方式),即使文档,数组在变量名称之前用括号声明:

 int[] array1; 

注意:注意“声明” 不是 “初始化”(或实例化

 int[] array1; // declares an array of int named "array1" // at this point, "array1" is NOT an array, but null // Thus we "declare" a variable that will hold some // data of type int[]. array1 = new int[] {1, 2, 3}; // legacy initialization; set an array of int // with 3 values to "array1". Thus, we "initialize" // the variable with some data of type int[] 

因此,

 int [] array1; int array2[]; 

都声明了两个int[]类型的变量; 但是,它们只是数据类型的声明,而不是数组。 就像Oscar Gomez所说,现在的区别在于第二种“方式”要求你指定变量是数组类型,而不仅仅是int。

 int i[], j; // i is a data type array of int, while j is only an int int [] k, l; // both k and l are of the same type: array of int 

数组由数组创建表达式数组初始值设定项 创建 。 前者适用于array2虽然在这种情况下,提供了数组初始值设定项 ),而后者适用于array1

有关更多信息,请参阅:

  • JLS,§10.3 – 数组创建
  • JLS,§10.6 – 数组初始化器
  • JLS,§15.10 – 数组创建表达式