我需要一个n维度的场,其中n基于构造函数的输入。但我甚至不确定这是否可能。是吗?
我需要一个n维度的场,其中n基于构造函数的输入。但我甚至不确定这是否可能。是吗?
ArrayList
,它包含多个ArrayList
,这些ArrayList
可以一直嵌套下去。然而,这样使用起来可能会很麻烦。class NDimensionalArray {
private Object[] array; // internal representation of the N-dimensional array
private int[] dimensions; // dimensions of the array
private int[] multipliers; // used to calculate the index in the internal array
NDimensionalArray(int... dimensions) {
int arraySize = 1;
multipliers = new int[dimensions.length];
for (int idx = dimensions.length - 1; idx >= 0; idx--) {
multipliers[idx] = arraySize;
arraySize *= dimensions[idx];
}
array = new Object[arraySize];
this.dimensions = dimensions;
}
...
public Object get(int... indices) {
assert indices.length == dimensions.length;
int internalIndex = 0;
for (int idx = 0; idx < indices.length; idx++) {
internalIndex += indices[idx] * multipliers[idx];
}
return array[internalIndex];
}
...
}
List<List<List...<String>>>
,但对于7个维度,则需要List<List<List<List<List<List<List...<String>>>>>>>
。同样,所有元素(即内部列表)将是不同类型的 - 代码中无法以统一的方式处理这种情况。 - Péter Törökjava.lang.reflect.Array
还包含另一个newInstance
方法来创建多维数组。例如:int[] dimensions = { 10, 10, 10 }; // 3-dimensional array, 10 elements per dimension
Object myArray = Array.newInstance(String.class, dimensions); // 3D array of strings
由于维数在运行时未知,因此只能将数组作为 Object
处理,并且必须使用 Array
类的 get
和 set
方法来操作数组的元素。
i1 + dim1 + (i2 + dim2 * (....))
,这可以使用简单的循环完成。 - maaartinus