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]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP