Hem*_*mer 5 java arrays multidimensional-array
我想知道最简单的方法是实现一个在运行时指定排名的数组.
我正在处理的示例存储了格点的布尔值数组,我希望用户能够选择模型在运行时使用的空间维数.
我查看了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);
Run Code Online (Sandbox Code Playgroud)
但是以任何方式访问这些值似乎需要非常慢的方法,例如递归使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1685 次 |
| 最近记录: |