我想知道实现一个在运行时指定等级的数组的最简单方法是什么。
我正在处理的示例存储格点的 boolean 值数组,我希望用户能够选择模型在运行时使用的空间维度数。
我查看了 Array.newInstance() 方法:
dimensionOfSpace = userInputValue; // this value comes from GUI or whatever
int latticeLength = 5; // square lattice for simplicity
int[] dimensions = new int[dimensionOfSpace];
for(int i = 0; i < l.length; i++) l[i] = length;
Object lattice = Array.newInstance(boolean.class, dimensions);
但以任何方式访问这些值似乎都需要非常慢的方法,例如递归使用 Array.get 直到返回值不再是数组,即使用 isArray()。
我在这里缺少明显的解决方案吗?我希望能够以类似于 foo[i][j][k] 的方式访问这些值。
最佳答案
看起来您正在寻找的是某种方法来声明数组在运行时的维数。我不知道如何使用多维 ArrayList 或任何必须在编译时指定维度的多维结构来完成此操作。
我看到的唯一答案是使用包装在一个类中的简单线性数组,该类将多维坐标与其在底层数组中的位置进行相互转换。这基本上就是 C 等语言通过使用一个连续的内存块来存储多维数组的方式。
代码看起来像这样:
import java.util.*;
class MultiArray<T>{
private int[] dimensions;
private Object[] array;
public MultiArray(int ... dimensions){
this.dimensions=dimensions;
//Utils.product returns the product of the ints in an array
array=new Object[Utils.product(dimensions)];
}
public void set(T value, int ... coords){
int pos=computePos(coords);
array[pos]=value;
}
public T get(int ... coords){
int pos=computePos(coords);
return (T)(array[pos]);
}
private int computePos(int[] coords){
int pos=0;
int factor=1;
for (int i=0;i<coords.length;i++){
pos+=factor*coords[i];
factor*=dimensions[i];
}
return pos;
}
}
class Main{
public static void main(String args[]){
MultiArray<Integer> m=new MultiArray<Integer>(new int[]{5,4,3});
Random r=new Random();
for(int i=0;i<5;i++)
for(int j=0;j<4;j++)
for(int k=0;k<3;k++)
m.set(r.nextInt(),i,j,k);
for(int i=0;i<5;i++){
for(int j=0;j<4;j++){
for(int k=0;k<3;k++)
System.out.print(m.get(i,j,k)+" ");
System.out.println("");
}
System.out.println("\n");
}
}
}
class Utils{
public static int product(int...a){
int ret=1;
for (int x:a) ret*=x;
return ret;
}
}
关于java - 在运行时设置数组的等级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2073674/