ske*_*gse 9 java constructor multidimensional-array
我需要能够有一个n维字段,其中n基于构造函数的输入.但我甚至不确定这是否可行.是吗?
快速的解决方案:你可以用非通用近似它ArrayList的ArrayList的...要深,因为你需要.但是,这可能会很快使用起来很尴尬.
需要更多工作的替代方法可以是使用底层平面数组表示来实现您自己的类型,您可以在其中内部计算索引,并为访问器方法提供vararg参数.我不确定它是否完全可行,但可能值得一试......
粗略的例子(没有测试,没有溢出检查,错误处理等,但希望传达基本的想法):
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];
}
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10080 次 |
| 最近记录: |