由于数组的大小是固定的,因此您不能动态地向其中添加元素。但是,如果您仍然想要这样做,将数组转换为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
myArray[i] = sc.next();
}
System.out.println(Arrays.toString(myArray));
ArrayList myList = new ArrayList(Arrays.asList(myArray));
System.out.println("输入要添加的元素:");
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]
输入要添加的元素:
Mahavir
[Ram, Rahim, Robert, Mahavir]