[英]What's the difference between two array declarations in Java?
在我的書中,他們一直在以下兩種方法之間切換聲明數組的方式:
int array1[] = {1, 2, 3};
int[] array2 = {1, 2, 3};
我想知道兩個括號的位置之間有什么區別,為什么當我將括號放在名稱后面(例如數組1)時,為什么必須將其初始化為一組值或一個新的數組,但是在array2中,我可以簡單地說“ int [] array2;” 然后再使用...?
它們是相同的,除了您提到的,如果您在名稱后面加上方括號,則必須對其進行初始化。 在名稱前聲明它們的優點之一是可以進行多個數組初始化,如下所示:
int [] myArray1, myArray2;
int myArray1[], myArray2[];
根據文檔的Java方法是將括號放在數組名稱之前。
它們之間都沒有區別,因為它們都聲明了一個“整數數組”類型的變量。 即使在文檔中,數組也沒有“ 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所說的,現在的區別是第二個“方式”要求您指定變量的類型為array,而不僅僅是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
。
有關更多信息,請參見:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.