如何在 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]
廣告