如何用 Java 建立陣列?


在 Java 中,你可以使用 new 關鍵字,建立陣列,其用法類似於建立一個物件。使用 new 關鍵字在 Java 中建立陣列的語法 −

type[] reference = new type[10];

其中,

  • 型別 是陣列中每個元素的資料型別。
  • 引用 是用來儲存陣列的變數。

而且,如果你想透過索引逐個為所有元素賦值,可以這樣填充陣列 −

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}

更新時間: 2020 年 2 月 19 日

2 個千以上的瀏覽量

啟動您的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.