如何在 Java 中建立一個數組?
在 Java 中,你可以使用 new 關鍵字像建立物件一樣建立陣列。使用 new 關鍵字在 Java 中建立陣列的語法為 -
type[] reference = new type[10];
其中,
- type 是陣列元素的資料型別。
- reference 是儲存陣列的引用。
並且,如果你想透過使用索引逐個向所有元素賦值來填充陣列 -
reference [0] = value1; reference [1] = value2;
例如,如果你想建立一個包含 5 個元素的整數陣列,可以使用 new 關鍵字來建立 -
int[] myArray = new int[5]; You can populate the array element by element using the array index: myArray [0] = 101; myArray [1] = 102; You can also create and initialize an array directly using the flower brackets ({}). int [] myArray = {10, 20, 30, 40, 50}
廣告