Java 中的可變長度(動態)陣列是什麼?


在 Java 中,陣列是固定長度的。陣列的大小將在建立時決定。但是,如果你仍想建立可變長度的陣列,可以使用諸如陣列列表之類的集合來實現。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class AddingItemsDynamically {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array :: ");
      int size = sc.nextInt();
      String myArray[] = new String[size];
      System.out.println("Enter elements of the array (Strings) :: ");
      for(int i=0; i<size; i++) {
         myArray[i] = sc.next();
      }
      System.out.println(Arrays.toString(myArray));
      ArrayList<String> myList = new ArrayList<String>(Arrays.asList(myArray));
      System.out.println("Enter the element that is to be added:");
      String element = sc.next();
      myList.add(element);
      myArray = myList.toArray(myArray);
      System.out.println(Arrays.toString(myArray));
   }
}

輸出

Enter the size of the array ::
3
Enter elements of the array (Strings) ::
Ram
Rahim
Robert
[Ram, Rahim, Robert]
Enter the element that is to be added:
Mahavir
[Ram, Rahim, Robert, Mahavir]

更新於:2020 年 2 月 19 日

4K+ 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.