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