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]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP