如何在 Java 中初始化動態陣列?


以下程式展示如何初始化之前宣告的陣列。

示例

public class Tester {
   int a[];
   public static void main(String[] args) {
      Tester tester = new Tester();
      tester.initialize();
   }
   private void initialize() {
      a = new int[3];
      a[0] = 0;
      a[1] = 1;
      a[2] = 2;
      for(int i=0; i< a.length ; i++) {
         System.out.print(a[i] +" ");
      }
   }
}

輸出

0 1 2

更新於:24-2 月-2020

500 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告