如何在 Java 中動態將項新增到陣列中?
由於陣列的大小是固定的,因此你不能動態地向其中新增元素。但是,如果你仍然想這樣做,則:
- 將陣列轉換為 ArrayList 物件。
- 將所需的元素新增到陣列列表中。
- 將陣列列表轉換為陣列。
示例
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]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP