假设我收到一个我们在收到之前不知道的号码,比如5,然后是一系列长度为5的号码:2,2,3,2,2
。
然后,我们构建一个数组[2][2][3][2][2]
。
有没有办法在Java中执行此操作?
答案 0 :(得分:0)
动态多维数组创建示例:
String input = "5 2 2 3 2 2";
Scanner sc = new Scanner(input);
int dimCount = sc.nextInt();
int[] dims = new int[dimCount];
for (int i = 0; i < dimCount; i++)
dims[i] = sc.nextInt();
Object multiDimArray = java.lang.reflect.Array.newInstance(int.class, dims);
现在你只需要继续使用java.lang.reflect.Array
来操作它,因为你在编译时不知道它有多少维度。